我如何定义类对象的普通控制台输出(vs. __str__)?



当定义我自己的类时,我可以覆盖__str__来定义它的print(my_class)行为。我要做什么来覆盖行为时,只是调用一个my_class对象?

结果:

> obj = my_class("ABC") # define
> print(obj)            # call with print
'my class with ABC'
> obj                   # call obj only
'<__console__.my_class object at 0x7fedf752398532d9d0>'

我想要的(例如obj返回与print(obj)相同或其他一些手动定义的文本)。

> obj                   # when obj is called plainly, I want to define its default
'my class with ABC (or some other default representation of the class object)'

:

class my_class:
def __init__(self, some_string_argument)
self.some_string = some_string_argument
def __str__(self): # 
return f"my_class with {self.some_string}"

Magic method__repr__就是其中一个。但这是不鼓励的。一般来说,__str__对于最终用户来说应该是可以理解的,__repr__应该返回一个字符串,当传递给eval时,将产生一个为其定义的对象的有效实例。

class A:
def __repr__(self):
return "I'm A!"
a = A()
a # This will print "I'm A!"

它应该/可能是什么:

class A:
def __repr__(self):
return "A()"
a = A()
a_repr = a.__repr__()
b = eval(a_repr) # "b" is an instance of class A in this case

最新更新