gpt4 book ai didi

Python交互式shell : how do I know what method gets used when I simply type the name of an object?

转载 作者:行者123 更新时间:2023-12-01 08:53:55 27 4
gpt4 key购买 nike

当它是字符串或数字时,很清楚,分别打印

A="这是一个字符串"
B=3

A
this is a string
B
3

如果我有更复杂的对象怎么办?我问这个是因为我正在学习一个模块并且

A.name 
B.name

结果为一行(实际上覆盖了先前的输入)而

print (A.name)
print (B.name)

结果分为两行(正常行为)

最佳答案

如果您只是将一个对象放入控制台,__repr__ 方法将被调用,您将看到该方法返回的任何内容。显式打印使用__str__。如果没有 __str__print 将回退到 __repr__

演示:

>>> class A:
... def __repr__(self):
... return '__repr__'
... def __str__(self):
... return '__str__'
...
>>> a = A()
>>> a
__repr__
>>> print(a)
__str__
>>> del A.__str__
>>> a
__repr__
>>> print(a)
__repr__
>>> del A.__repr__
>>> a
<__main__.A object at 0x7f4bdf0034a8>
>>> print(a)
<__main__.A object at 0x7f4bdf0034a8>

关于Python交互式shell : how do I know what method gets used when I simply type the name of an object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com