我有兴趣在intPython 中继承内置类型(我使用的是2.5版),但是在初始化工作时遇到了一些麻烦.
这是一些示例代码,应该是相当明显的.
class TestClass(int):
def __init__(self):
int.__init__(self, 5)
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用它时,我得到:
>>> a = TestClass()
>>> a
0
Run Code Online (Sandbox Code Playgroud)
在哪里我期待结果5.
我究竟做错了什么?到目前为止,谷歌并没有太大的帮助,但我不确定我应该寻找什么
我得到了以下课程:
class ConstraintFailureSet(dict, Exception) :
"""
Container for constraint failures. It act as a constraint failure itself
but can contain other constraint failures that can be accessed with a dict syntax.
"""
def __init__(self, **failures) :
dict.__init__(self, failures)
Exception.__init__(self)
print isinstance(ConstraintFailureSet(), Exception)
True
raise ConstraintFailureSet()
TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet
Run Code Online (Sandbox Code Playgroud)
有没有搞错 ?
最糟糕的是我不能尝试super(),因为Exception是基于旧的类......
编辑:是的,我试图切换继承/ init的顺序.
编辑2:我在Ubuntu8.10上使用CPython 2.4.你刚才知道这种信息是有用的;-).无论如何,这个小谜语已经关闭了我同事的三个口.你将成为我当天最好的朋友......
在Python中,我试图扩展内置'int'类型.这样做我想将一些keywoard参数传递给构造函数,所以我这样做:
class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
Run Code Online (Sandbox Code Playgroud)
虽然调用C(3)工作正常,但C(3, a=4)给出:
'a' is an invalid keyword argument for this function`
Run Code Online (Sandbox Code Playgroud)
并C.__mro__返回预期的:
(<class '__main__.C'>, <type 'int'>, <type 'object'>)
Run Code Online (Sandbox Code Playgroud)
但似乎Python试图先打电话int.__init__......任何人都知道为什么?这是解释器中的错误吗?
让我们先说这个问题,你应该使用__new__而不是__init__用于子类化不可变对象.
话虽如此,让我们看看以下代码:
class MyTuple(tuple):
def __init__(self, *args):
super(MyTuple, self).__init__(*args)
mytuple = MyTuple([1,2,3])
Run Code Online (Sandbox Code Playgroud)
这适用于python2,但在python3中,我得到:
Traceback (most recent call last):
File "tmp.py", line 5, in <module>
mytuple = MyTuple([1,2,3])
File "tmp.py", line 3, in __init__
super(MyTuple, self).__init__(*args)
TypeError: object.__init__() takes no parameters
Run Code Online (Sandbox Code Playgroud)
为什么会这样?python3有什么变化?
python ×4
subclass ×2
class-design ×1
inheritance ×1
overriding ×1
python-2.5 ×1
python-3.x ×1
tuples ×1