在python中,如果要定义对象的字符串表示形式,则可以执行以下操作:
class Person:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def __str__(self):
return f'{self.first} {self.last}, {self.age} years old'
person_1 = Person('John', 'Smith', 25)
现在,如果您输入print(person_1)
或str(person_1)
,则会得到John Smith, 25 years old
。
如果__str__
方法不存在,则输出为<__main__.Person object at 0x104e12e20>
我如何迅速做同样的事情?] >>
当然,我可以定义一个我想要的名称的方法,然后在对象上调用它,但是它缺少语法糖。
在python中,如果要定义对象的字符串表示形式,则可以执行以下操作:类Person:def __init __(self,first,last,age):self.first = first self.last = ...
仅符合CustomStringConvertible
协议。您要做的就是实现description
属性。