为什么我在创建继承自 str(或也继承自 int)的类时遇到问题
class C(str):
def __init__(self, a, b):
str.__init__(self,a)
self.b = b
C("a", "B")
TypeError: str() takes at most 1 argument (2 given)
如果我尝试使用 int
而不是 str
,也会发生同样的情况,但它适用于自定义类。我需要使用 __new__
而不是 __init__
?为什么?
最佳答案
>>> class C(str):
... def __new__(cls, *args, **kw):
... return str.__new__(cls, *args, **kw)
...
>>> c = C("hello world")
>>> type(c)
<class '__main__.C'>
>>> c.__class__.__mro__
(<class '__main__.C'>, <type 'str'>, <type 'basestring'>, <type 'object'>)
由于__init__
是在对象构造完成后调用的,所以修改不可变类型的值已经来不及了。注意 __new__
是一个类方法,所以我调用了第一个参数 cls
见 here了解更多信息
>>> class C(str):
... def __new__(cls, value, meta):
... obj = str.__new__(cls, value)
... obj.meta = meta
... return obj
...
>>> c = C("hello world", "meta")
>>> c
'hello world'
>>> c.meta
'meta'
关于python - 从 str 或 int 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673651/