使用类型创建class时如何定义__str__函数?
How to define the __str__ function while using type to create a class?
我正在尝试实现以下情况:
class ABCD(object):
def __str__(self):
return "some string"
a=ABCD()
print a
some string
使用类型:
A=type("A",(object,),dict(__str__="some string",h=5))
a=A()
print a
但是出现如下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
您是要传递回调吗? __str__
将作为 实例方法 实现,即 returns 一个字符串。
A = type("A",(object,), dict(__str__=lambda self: "some string" , h=5))
a = A()
print(a)
some string
当您在一个对象上调用 print
时,它的 __str__
方法也会被调用。如果对象没有定义,则调用 object
class 的 __str__
。因此,您不应将字符串分配给 __str__
,因为 python 会尝试将其作为函数 "call",抛出 TypeError
。
我正在尝试实现以下情况:
class ABCD(object):
def __str__(self):
return "some string"
a=ABCD()
print a
some string
使用类型:
A=type("A",(object,),dict(__str__="some string",h=5))
a=A()
print a
但是出现如下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
您是要传递回调吗? __str__
将作为 实例方法 实现,即 returns 一个字符串。
A = type("A",(object,), dict(__str__=lambda self: "some string" , h=5))
a = A()
print(a)
some string
当您在一个对象上调用 print
时,它的 __str__
方法也会被调用。如果对象没有定义,则调用 object
class 的 __str__
。因此,您不应将字符串分配给 __str__
,因为 python 会尝试将其作为函数 "call",抛出 TypeError
。