str__和__repr
如果要把一个类的实例变成 str,就需要实现特殊方法__str__():
class Person(object):
def init(self, name, gender):
self.name = name
self.gender = gender
def str(self):
return ‘(Person: %s, %s)’ % (self.name, self.gender)
p = Person(‘Bob’, ‘male’)
print p
(Person: Bob, male)
但是,如果直接敲变量 p:
p
似乎__str__() 不会被调用。
class Tweet:
def init(self, who: str, when: date, what: str) -> None:
self.userid = who
self.content = what
self.created_at = when
self.likes = 0
def str(self):
return ’ %s, %s’ % (self.userid, self.content)
repr = str
t1=Tweet(‘Rukhsana’, date(2017, 9, 16), ‘Hey!’)
t1
Rukhsana, Hey!