gpt4 book ai didi

python 方法窃取器

转载 作者:太空狗 更新时间:2023-10-29 22:23:09 27 4
gpt4 key购买 nike

如何从一个类“窃取”或复制一个方法到另一个类?

示例代码:

class A(object):
def foo(self):
print "blah"


class B(object):
foo = A.foo

B().foo()

预期输出:

"blah"

相反:

TypeError: unbound method foo() must be called with A instance as first argument (got nothing instead)

最佳答案

使用__func__:

>>> A.foo
<unbound method A.foo>
>>> A.foo.__func__
<function foo at 0x00BC5F70>
>>> class B(object):
... foo = A.foo.__func__
...
>>> B().foo()
"blah"

引用 the docs :

An instance method object combines a class, a class instance and any callable object (normally a user-defined function).

Special read-only attributes: __self__ is the class instance object, __func__ is the function object; __doc__ is the method’s documentation (same as __func__.__doc__); __name__ is the method name (same as __func__.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.

关于python 方法窃取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13537828/

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