我们将研究两个重要的python对象函数,它们在调试python代码时非常有用登录中有关对象的有用信息。
Python语法
此方法返回一串对象的表示。当打印()
或str()
function is invoked on an object.
此方法必须返回字符串对象。如果我们不为一个类实现u str_uu()函数,那么将使用内置的对象实现来实际调用u repr_uu()函数。
Python()
函数返回对象表示。它可以是任何有效的python表达式,例如元组,词典,字符串等。
当repr()
function is invoked on the object, in that case, __repr__() function must return a String otherwise error will be thrown.
Python的str和repr示例
这两个函数都在调试中使用,让我们看看如果不为对象定义这些函数会发生什么。
class Person:
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
p = Person("Pankaj", 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)+ ")"
请注意,我们返回的dict是针对uurepruuu函数。让我们看看如果我们使用这些方法会发生什么。
p = Person("Pankaj", 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=Pankaj, age=34)
Person(name=Pankaj, age=34)
Person(name=Pankaj, age=34)
{"name": "Pankaj", "age": 34}
<class "dict">
File "/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/str_repr_functions.py", line 29, in <module>
print(repr(p))
TypeError: __repr__ returned non-string (type dict)
请注意,repr()函数正在抛出TypeError
since our __repr__ implementation is returning dict and not string.
让’;更改repr_uu函数的实现,如下所示:
def __repr__(self):
return "{name:"+self.name+", age:"+str(self.age)+ "}"
现在它返回字符串,对象表示调用的新输出将是:
{name:Pankaj, age:34}
<class "str">
{name:Pankaj, age:34}
前面我们提到过,如果我们不实现函数,那么就会调用函数。只需从Person类和print(p)
will print {name:Pankaj, age:34}
.
函数之间的区别
- __str_uu必须返回string对象,而uurepr_uu可以返回任何python表达式。
- 如果缺少实现,则使用函数作为回退。如果缺少函数实现,则没有回退。
- 如果函数返回的是对象的字符串表示,则可以跳过函数的实现。
摘要
两个函数非常相似。我们可以获得字符串格式的对象表示以及其他特定格式(如tuple和dict)来获取有关对象的信息。
您可以从我们的GitHub存储库.