从 str 或 int 继承 [英] inheritance from str or int
本文介绍了从 str 或 int 继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我在创建从 str(或也从 int)继承的类时遇到问题
C 类(str):def __init__(self, a, b):str.__init__(self,a)自我.b = bC(a",B")类型错误:str() 最多接受 1 个参数(给定 2 个)
如果我尝试使用 int
而不是 str
,也会发生同样的情况,但它适用于自定义类.我需要使用 __new__
而不是 __init__
吗?为什么?
解决方案
>>>C类(str):... def __new__(cls, *args, **kw):...返回 str.__new__(cls, *args, **kw)...>>>c = C("你好世界")>>>类型(c)<类'__main__.C'>>>>c.__class__.__mro__(<class '__main__.C'>, <type 'str'>, <type 'basestring'>, <type 'object'>)
由于__init__
是在对象被构造后调用的,所以修改不可变类型的值已经来不及了.注意 __new__
是一个类方法,所以我调用了第一个参数 cls
请参阅此处了解更多信息
<预><代码>>>>C类(str):... def __new__(cls, value, meta):... obj = str.__new__(cls, value)... obj.meta = 元...返回对象...>>>c = C("你好世界", "元")>>>C'你好世界'>>>元'元'Why I have problem creating a class inheriting from str (or also from 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)
the same happens if I try to use int
instead of str
, but it works with custom classes. I need to use __new__
instead of __init__
? why?
解决方案
>>> 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'>)
Since __init__
is called after the object is constructed, it is too late to modify the value for immutable types. Note that __new__
is a classmethod, so I have called the first parameter cls
See here for more information
>>> 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'
这篇关于从 str 或 int 继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文