从str或int继承
发布于 2021-01-29 16:18:14
为什么我在创建从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__
?为什么?
关注者
0
被浏览
44
1 个回答
-
>>> 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
看到这里了解更多信息
>>> 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'