python类方法的属性问题

2024-04-19 07:12:40 发布

您现在位置:Python中文网/ 问答频道 /正文

class test :

    def fn(self, i):
        #test.fn.f = 0     the "compiler" show "not define" errors
        #self.fn.f = 0     the "compiler" show "not define" errors

        return test.fn.f   #ok
        return self.fn.f   #ok

    fn.f = 1

p = test()

print p.fn(1)

我只是好奇为什么不能在“fn”方法中更改属性的值

本质上,这是。。。你知道吗

test.fn.fself.fn.f之间有什么区别?我确信修改函数的属性值是可以的,但是为什么我可以在方法中这样做呢?你知道吗


Tags: the方法testselfreturn属性compilerdef
2条回答

发生的情况如下:

fn.f = 1给函数本身一个属性。你知道吗

但是在使用test.fnself.fn进行访问时,不会得到函数本身,而是一个instancemethod。为什么?因为在类中进行属性访问时,如果存在任何方法,就会调用组件的__get__方法。就函数而言,就是这样。你知道吗

如果调用函数的__get__方法,则将其转换为绑定或未绑定的实例方法,该方法只是函数的包装器。你知道吗

你能应付的

test.fn.im_func.f = 1
self.fn.im_func.f = 1

不能将任意属性分配给instancemethod。赋值在类体中起作用,因为此时它仍然是function;直到在块的末尾创建类,它才成为instancemethod。你知道吗

相关问题 更多 >