当前位置 博文首页 > RunningOnMyWay的博客:Python3基础学习----定制类
>>> a = 3.3
>>> type(a)
<class 'float'>
float类型其实也是一种类,因此可以通过class定义去定制一个类。
如何创建定制类,关键用到两个特殊方法__repr__ 与__str__
示例代码如下:
>>> class Person:
def __init__(self,name,word):
self.name = name
self.word = word
def __str__(self):
return "{0}说过:{1}".format(self.name,self.word)
def __repr__(self):
return "他是{0}".format(self.name)
>>> p1 = Person("爱因斯坦","不要努力做一个成功者,而要做一个有价值的人。")
>>> p1
他是爱因斯坦
>>> print(p1)
爱因斯坦说过:不要努力做一个成功者,而要做一个有价值的人。
>>> type(p1)
<class '__main__.Person'>
通过上方的示例代码看出,随口一说就是一个给机器看的一个给人看的,即__str__用于用户易读,而__repr__用于解释器,解析器友好