sq6ra
sq6ra

Reputation: 23

problems about the attributes of a python class method

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)

I am just curious about why i can't change the values of a attribute in "fn" method

In essence, it's...

what differences are between test.fn.f and self.fn.f ? i am sure it's ok modifing function's attribute-value , but why i can do that in a method?

Upvotes: 2

Views: 103

Answers (2)

glglgl
glglgl

Reputation: 91049

What happens is the following:

fn.f = 1 gives the function itself an attribute.

But on access with test.fn and self.fn, you don't get the function itself, but an instancemethod. Why? Because on attribute access in a class, the component's __get__ method is called if there is any. In the case of functions, this is the case.

If you call a function's __get__ method, you turn it into a bound or unbound instance method which is just a wrapper around the function.

You can cope with that with

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

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You can't assign arbitrary attributes to an instancemethod. The assignment works within the class body since it's still a function at that point; it doesn't become an instancemethod until the class is created at the end of the block.

Upvotes: 1

Related Questions