gpt4 book ai didi

python - 是否可以在 Python 中覆盖 namedtuple 中的方法?

转载 作者:行者123 更新时间:2023-11-28 21:49:54 25 4
gpt4 key购买 nike

假设我有这样一个类:

class Foo(namedtuple('Foo', ['f1'])):
def f1(self):
print('Default f1')

def __new__(cls, f1=f1):
return super().__new__(cls, f1)

假设我稍后创建了一个 Foo 对象并选择覆盖 f1 的方法定义,如下所示:

def my_f1():
print("My f1")

foo = Foo(f1=my_f1)

如果我再尝试:

foo.f1()

我得到:

Default f1

当然,我正在尝试打印“My f1”。我也希望 f1 是可选的。这里发生了什么?是否可以在 namedtuple 中为方法定义默认实现,然后在 new 中覆盖它?

最佳答案

您不能让一个方法和一个插槽使用相同的名称。命名元组使用 slots ,并且这些被实现为 property 对象在与方法相同的命名空间中。通过定义 f1 方法,您破坏了 f1 属性:

>>> from collections import namedtuple
>>> namedtuple('Foo', ['f1']).f1
<property object at 0x1069764c8>
>>> class Foo(namedtuple('Foo', ['f1'])):
... def f1(self):
... print('Default f1')
...
>>> Foo.f1
<unbound method Foo.f1>

property 对象只返回 self[0]。因此,要么按位置访问 f1 值:

class Foo(namedtuple('Foo', ['f1'])):
def f1(self):
if self[0]:
return self[0]()
print('Default f1')

或者给你的属性一个不同的名称,并让 f1 方法委托(delegate)给它:

class Foo(namedtuple('Foo', ['f1_callable'])):
def f1(self):
if self.f1_callable:
return self.f1_callable()
print('Default f1')

演示:

>>> def my_f1():
... print("My f1")
...
>>> class Foo(namedtuple('Foo', ['f1'])):
... def f1(self):
... if self[0]:
... return self[0]()
... print('Default f1')
...
>>> foo = Foo(my_f1)
>>> foo.f1()
My f1
>>> foo = Foo(None)
>>> foo.f1()
Default f1

关于python - 是否可以在 Python 中覆盖 namedtuple 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785448/

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