使用多个__init__参数对Python元组进行子类化 [英] Subclassing Python 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
或元组
)自定义
实例创建。在
的自定义元类中,通常也会为
重写,以自定义类创建。
__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__参数对Python元组进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!