Python __str __()和__repr __()函数
时间:2020-02-23 14:43:22 来源:igfitidea点击:
我们将研究两个重要的python对象函数,它们通过记录有关对象的有用信息对调试python代码非常有帮助。
Python __str __()
此方法返回对象的字符串表示形式。
在对象上调用print()
或者str()
函数时将调用此方法。
此方法必须返回String对象。
如果我们不为类实现__str __()函数,则使用实际调用__repr __()函数的内置对象实现。
Python __repr __()
Python __repr __()函数返回对象表示形式。
它可以是任何有效的python表达式,例如元组,字典,字符串等。
在对象上调用repr()
函数时将调用此方法,在这种情况下,__repr __()函数必须返回String,否则将引发错误。
Python __str__和__repr__示例
这两个函数都用于调试,让我们看看如果不为对象定义这些函数会发生什么。
class Person: name = "" age = 0 def __init__(self, personName, personAge): self.name = personName self.age = personAge p = Person('hyman', 34) print(p.__str__()) print(p.__repr__())
输出:
<__main__.Person object at 0x10ff22470> <__main__.Person object at 0x10ff22470>
如您所见,默认实现是无用的。
让我们继续实施这两种方法。
class Person: name = "" age = 0 def __init__(self, personName, personAge): self.name = personName self.age = personAge def __repr__(self): return {'name':self.name, 'age':self.age} def __str__(self): return 'Person(name='+self.name+', age='+str(self.age)+ ')'
注意,我们将为__repr__函数返回dict。
让我们看看如果使用这些方法会发生什么。
p = Person('hyman', 34) # __str__() example print(p) print(p.__str__()) s = str(p) print(s) # __repr__() example print(p.__repr__()) print(type(p.__repr__())) print(repr(p))
输出:
Person(name=hyman, age=34) Person(name=hyman, age=34) Person(name=hyman, age=34) {'name': 'hyman', 'age': 34} <class 'dict'> File "/Users/hyman/Documents/PycharmProjects/BasicPython/basic_examples/str_repr_functions.py", line 29, in <module> print(repr(p)) TypeError: __repr__ returned non-string (type dict)
注意,由于我们的__repr__实现返回的是dict而不是字符串,因此repr()函数会抛出" TypeError"。
让我们如下更改__repr__函数的实现:
def __repr__(self): return '{name:'+self.name+', age:'+str(self.age)+ '}'
现在它返回String,对象表示调用的新输出将是:
{name:hyman, age:34} <class 'str'> {name:hyman, age:34}
之前我们提到过,如果不实现__str__函数,则会调用__repr__函数。
只需注释Person类的__str__函数实现,然后print(p)将打印{name:hyman,age:34}。
__str__和__repr__函数之间的区别
__str__必须返回字符串对象,而__repr__可以返回任何python表达式。
如果缺少__str__实现,则将__repr__函数用作后备。
如果缺少__repr__函数实现,则没有回退。如果__repr__函数返回对象的字符串表示形式,则可以跳过__str__函数的实现。