gpt4 book ai didi

python - 当类中嵌入的函数是类的 "method"时?

转载 作者:太空狗 更新时间:2023-10-30 02:23:22 25 4
gpt4 key购买 nike

执行时...

class A:
def b(self, a):
print a
print dir(b)
print dir(A.b)

它给出了结果:

['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure',
'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self']

为什么不同?

最佳答案

Python 2 中,第二种情况返回一个未绑定(bind)的方法,第一种情况返回一个函数。来自 the documentation ,强调我的:

User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.

所以你得到一个方法纯粹是因为 A. 前缀。原始函数仍然可以通过方法的 im_func(或者从 2.6 开始也可以是 __func__)访问。另请注意,每次访问都会获得一个新方法对象,因此 A.b is A.b 返回 False!

Python 3 中,未绑定(bind)方法不再作为单独的类型存在,您将从两个打印调用中获得相同的输出:

$ python3
Python 3.1.2 (release31-maint, Sep 17 2010, 20:27:33)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def b(self, a):
... print(a)
... print(dir(b))
...
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> print(dir(A.b))
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

如果将 dir 替换为 id,您会发现在 Python 3 中,这两种情况下它是完全相同的函数对象。

关于python - 当类中嵌入的函数是类的 "method"时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4296477/

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