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.f
和self.fn.f
之间有什么区别?我确信修改函数的属性值是可以的,但是为什么我可以在方法中这样做呢?你知道吗
发生的情况如下:
fn.f = 1
给函数本身一个属性。你知道吗但是在使用
test.fn
和self.fn
进行访问时,不会得到函数本身,而是一个instancemethod
。为什么?因为在类中进行属性访问时,如果存在任何方法,就会调用组件的__get__
方法。就函数而言,就是这样。你知道吗如果调用函数的
__get__
方法,则将其转换为绑定或未绑定的实例方法,该方法只是函数的包装器。你知道吗你能应付的
不能将任意属性分配给
instancemethod
。赋值在类体中起作用,因为此时它仍然是function
;直到在块的末尾创建类,它才成为instancemethod
。你知道吗相关问题 更多 >
编程相关推荐