gpt4 book ai didi

python - 使用多个 __init__ 参数子类化元组

转载 作者:IT老高 更新时间:2023-10-28 20:31:24 24 4
gpt4 key购买 nike

以下代码有效:

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__:

python docs

object.__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).

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.

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__().

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

__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.

关于python - 使用多个 __init__ 参数子类化元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1565374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com