Python __str __()和__repr __()函数

We will look into two important python object functions that are very helpful in debugging python code by logging useful information regarding the object.

我们将研究两个重要的python对象函数,它们通过记录有关对象的有用信息对调试python代码非常有帮助。

Python __str __() (Python __str__())

This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

此方法返回对象的字符串表示形式。 在对象上调用print()str()函数时,将调用此方法。

This method must return the String object. If we don’t implement __str__() function for a class, then built-in object implementation is used that actually calls __repr__() function.

此方法必须返回String对象。 如果我们不为类实现__str __()函数,则使用实际调用__repr __()函数的内置对象实现。

Python __repr __() (Python __repr__())

Python __repr__() function returns the object representation. It could be any valid python expression such as tuple, dictionary, string etc.

Python __repr __()函数返回对象表示形式。 它可以是任何有效的python表达式,例如元组字典 ,字符串等。

This method is called when repr() function is invoked on the object, in that case, __repr__() function must return a String otherwise error will be thrown.

在对象上调用repr()函数时将调用此方法,在这种情况下,__repr __()函数必须返回String,否则将引发错误。

Python __str__和__repr__示例 (Python __str__ and __repr__ example)

Both of these functions are used in debugging, let’s see what happens if we don’t define these functions for an object.

这两个函数都用于调试,让我们看看如果不为对象定义这些函数会发生什么。

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__())

Output:

输出:

<__main__.Person object at 0x10ff22470>
<__main__.Person object at 0x10ff22470>

As you can see that the default implementation is useless. Let’s go ahead and implement both of these methods.

如您所见,默认实现是无用的。 让我们继续实现这两种方法。

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)+ ')'

Notice that we are returning dict for __repr__ function. Let’s see what happens if we use these methods.

注意,我们将为__repr__函数返回dict。 让我们看看如果使用这些方法会发生什么。

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))

Output:

输出:

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)

Notice that repr() function is throwing TypeError since our __repr__ implementation is returning dict and not string.

注意,由于我们的__repr__实现返回的是dict而不是字符串,因此repr()函数TypeError

Let’s change the implementation of __repr__ function as follows:

让我们如下更改__repr__函数的实现:

def __repr__(self):
        return '{name:'+self.name+', age:'+str(self.age)+ '}'

Now it’s returning String, and the new output for object representation calls will be:

现在,它返回String,对象表示调用的新输出将是:

{name:Pankaj, age:34}
<class 'str'>
{name:Pankaj, age:34}

Earlier we mentioned that if we don’t implement __str__ function then the __repr__ function is called. Just comment the __str__ function implementation from Person class and print(p) will print {name:Pankaj, age:34}.

前面我们提到如果不实现__str__函数,则将调用__repr__函数。 只需注释Person类的__str__函数实现, print(p)将显示{name:Pankaj, age:34}

__str__和__repr__函数之间的区别 (Difference between __str__ and __repr__ functions)

  1. __str__ must return string object whereas __repr__ can return any python expression.

    __str__必须返回字符串对象,而__repr__可以返回任何python表达式。
  2. If __str__ implementation is missing then __repr__ function is used as fallback. There is no fallback if __repr__ function implementation is missing.

    如果缺少__str__实现,则将__repr__函数用作后备。 如果缺少__repr__函数实现,则没有回退。
  3. If __repr__ function is returning String representation of the object, we can skip implementation of __str__ function.

    如果__repr__函数返回对象的字符串表示形式,则可以跳过__str__函数的实现。

摘要 (Summary)

Both __str__ and __repr__ functions are very similar. We can get the object representation in String format as well as other specific formats such as tuple and dict to get information about the object.

__str__和__repr__函数非常相似。 我们可以使用String格式以及其他特定格式(例如tuple和dict)来获取对象表示,以获取有关对象的信息。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/22460/python-str-repr-functions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值