gpt4 book ai didi

python - 在 Python 中使用 MethodType 的优点

转载 作者:太空狗 更新时间:2023-10-29 16:54:13 25 4
gpt4 key购买 nike

使用 types 模块中的 MethodType 有什么好处?您可以使用它向对象添加方法。但是我们可以在没有它的情况下轻松做到这一点:

def func():
print 1

class A:
pass

obj = A()
obj.func = func

即使我们通过运行 del func 删除主作用域中的 func,它仍然有效。

为什么要使用 MethodType?它只是一种约定还是一种良好的编程习惯?

最佳答案

事实上在运行时动态添加方法和你的例子很大:

  • 在你的情况下,你只是将一个函数附加到一个对象上,你当然可以调用它,但它是未绑定(bind)的,它与对象本身没有关系(即你不能在内部使用 self函数)
  • 添加 MethodType 时,您创建了一个绑定(bind) 方法,它的行为类似于该对象的普通 Python 方法,您必须首先将它所属的对象作为参数(通常称为 self ),您可以在函数内部访问它

这个例子展示了区别:

def func(obj):
print 'I am called from', obj
class A:
pass
a=A()
a.func=func
a.func()

这失败了 TypeError : func() takes exactly 1 argument (0 given) ,而此代码按预期工作:

import types
a.func = types.MethodType(func, a) # or types.MethodType(func, a, A) for PY2
a.func()

显示 I am called from <__main__.A instance at xxx>

关于python - 在 Python 中使用 MethodType 的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37455426/

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