如何通过方法透明地查看函数属性

Mad*_*ist 4 python methods attributes

我最近编写了许多需要标记属性的函数:

def fn1(): pass
fn1.mark = True
Run Code Online (Sandbox Code Playgroud)

实际的标记是由装饰者完成的,但它既不在这里也不在那里.我担心的是,当我以相同的方式在类中标记方法时,绑定方法时标记将不可见:

class A:
    def meth1(): pass
    meth1.mark = True
Run Code Online (Sandbox Code Playgroud)

但实际上该属性可见:

>>> fn1.mark
True
>>> A.meth1.mark
True
>>> A().meth1.mark
True
Run Code Online (Sandbox Code Playgroud)

但是,无法在绑定方法中分配或删除该属性,因为它可以在函数中:

>>> A().meth1.mark = False
AttributeError: 'method' object has no attribute 'mark'

>>> del A().meth1.mark
AttributeError: 'method' object has no attribute 'mark'
Run Code Online (Sandbox Code Playgroud)

方法的属性在绑定时如何变为可见?

use*_*ica 7

方法对象实现__getattribute__将未知属性的属性访问委托给底层函数对象.__setattr__但是,他们没有委托,这就是分配失败的原因.如果你想看到代码,它就method_getattroObjects/classobject.c.