使用多个__init__自变量对元组进行子类化 [英] Subclassing tuple with multiple __init__ arguments
问题描述
以下代码有效:
class Foo(tuple):
def __init__(self, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo([3, 4])
$ python play.py
结果:
play.py:4: DeprecationWarning: object.__init__() takes no parameters
super(Foo, self).__init__(tuple(b))
(3, 4)
但不是以下内容:
class Foo(tuple):
def __init__(self, a, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo(None, [3, 4])
$ python play.py
结果:
Traceback (most recent call last):
File "play.py", line 7, in <module>
print Foo(None, [3, 4])
TypeError: tuple() takes at most 1 argument (2 given)
为什么?
推荐答案
由于元组是不可变的,因此您必须改写__new__
:
Because tuples are immutable, you have to override __new__
instead:
object.__new__(cls[, ...])
被调用以创建一个新的实例
类别cls
. __new__()
是静态的
方法(特殊情况,因此您不需要
这样声明)
实例所在的类
要求作为其第一个论点.这
剩下的参数是那些通过的参数
到对象构造函数表达式
(对课程的调用).回报
__new__()
的值应该是新的
对象实例(通常是一个实例
(cls
).
Called to create a new instance of
class cls
. __new__()
is a static
method (special-cased so you need not
declare it as such) that takes the
class of which an instance was
requested as its first argument. The
remaining arguments are those passed
to the object constructor expression
(the call to the class). The return
value of __new__()
should be the new
object instance (usually an instance
of cls
).
典型的实现会创建一个新的
通过调用该类的实例
超类的__new__()
方法使用
super(currentclass, cls).__new__(cls[, ...])
,带有适当的参数,以及
然后修改新创建的
在返回之前根据需要实例
它.
Typical implementations create a new
instance of the class by invoking the
superclass’s __new__()
method using
super(currentclass, cls).__new__(cls[, ...])
with appropriate arguments and
then modifying the newly-created
instance as necessary before returning
it.
如果__new__()
返回的实例
cls
,然后是新实例的
__init__()
方法将像__init__(self[, ...])
一样被调用,其中self是新实例,其余实例
参数与传递的参数相同
到__new__()
.
If __new__()
returns an instance of
cls
, then the new instance’s
__init__()
method will be invoked like __init__(self[, ...])
, where self is the new instance and the remaining
arguments are the same as were passed
to __new__()
.
如果__new__()
不返回
cls
的实例,然后是新的
实例的__init__()
方法不会
被调用.
If __new__()
does not return an
instance of cls
, then the new
instance’s __init__()
method will not
be invoked.
__new__()
主要用于允许不可变类型的子类(例如
int
,str
或tuple
)进行自定义
实例创建.这也是普遍的
在以下的自定义元类中被覆盖
为了自定义类的创建.
__new__()
is intended mainly to allow subclasses of immutable types (like
int
, str
, or tuple
) to customize
instance creation. It is also commonly
overridden in custom metaclasses in
order to customize class creation.
这篇关于使用多个__init__自变量对元组进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!