gpt4 book ai didi

python - 如何在Python类中动态定义方法?

转载 作者:行者123 更新时间:2023-12-02 18:29:10 28 4
gpt4 key购买 nike

我想在我的类TestClass中定义许多方法。我想用他们的名字来调用它们 TestClass().method_1 ... TestClass().method_n.

我不想间接调用它们,例如通过像 TestClass().use_method('method_1', params) 这样的中间方法来调用它们,以保持与代码其他部分的一致性。

我想动态定义我的众多方法,但我不明白为什么这个最小的示例不起作用:

class TestClass:
def __init__(self):
method_names = [
'method_1',
'method_2']

for method_name in method_names:
def _f():
print(method_name)
# set the method as attribute
# (that is OK for me that it will not be
# a bound method)
setattr(
self,
method_name,
_f)
del _f

if __name__ == '__main__':
T = TestClass()

T.method_1()
T.method_2()

print(T.method_1)
print(T.method_2)

输出是:

function_2
function_2
<function TestClass.__init__.<locals>._f at 0x0000022ED8F46430>
<function TestClass.__init__.<locals>._f at 0x0000022EDADCE4C0>

在我期待的时候

function_1
function_2

我尝试在很多地方放置一些 copy.deepcopy 但没有帮助。

尝试用一个更简单的示例来缩小范围,我再次对结果感到惊讶:

class TestClass:
def __init__(self):
variable = 1

def _f():
print(variable)

del variable

setattr(
self,
'the_method',
_f)
del _f

variable = 2

if __name__ == '__main__':
T = TestClass()
T.the_method()

输出是2,而我期待的是1

关于正在发生的事情有任何提示吗?

----- 编辑以提供解决方案,感谢 the accepted answer from Tim Roberts (感谢卡片注意到类型(self)而不是 self-----

最小示例:

class TestClass:
def __init__(self):
variable = 1

def _f(captured_variable=variable):
print(captured_variable)
print(variable)

del variable

setattr(
type(self),
'the_method',
_f)
del _f

variable = 2

if __name__ == '__main__':
T = TestClass()
T.the_method()

输出是:

1
2

关于动态定义方法的原始问题:

class TestClass:
def __init__(self):
method_names = [
'method_1',
'method_2']

for method_name in method_names:
def _f(captured_method=method_name):

print(captured_method)
print(method_name)

# set the method as attribute
setattr(
type(self),
method_name,
_f)
del _f

if __name__ == '__main__':
T = TestClass()

T.method_1()
T.method_2()

print(T.method_1)
print(T.method_2)

输出是:

method_1
method_2
method_2
method_2
<function TestClass.__init__.<locals>._f at 0x000001D1CF9D6430>
<function TestClass.__init__.<locals>._f at 0x000001D1D187E4C0>

最佳答案

这是典型的 Python 错误之一。您获取变量的值,变量最终得到最终值。

您可以通过“捕获”变量的默认值来执行您想要的操作:

        for method_name in method_names:
def _f(method=method_name):
print(method)

关于python - 如何在Python类中动态定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69668425/

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