Many newbie questions regarding python

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Oct 8 12:01:36 CEST 2010


Rogério Brito wrote:
> class C:
>     f = 1
>     def g(self):
>         return f
>
> I get an annoying message when I try to call the g method in an object of type
> C, telling me that there's no global symbol called f. If I make g return self.f
> instead, things work as expected, but the code loses some readability.
>
> Is there any way around this or is that simply "a matter of life"?
>   
class C:
    f =1

creates the 'C.f ' name. When 'f' is used in g, you'll get then an error.

class C:
    f = 1
    def g(self):
        return C.f


is the obvious solution. However it can be slightly improved. f is a 
class attribute, meaning it's common to all instances of the C class. 
Thus g would be a class method, and is here declared liek a instance 
method (the instance being self).

class C:
    f = 1
    @classmethod
    def g(cls):
       return cls.f

c1 = C()
c2 = C()

print c1.f, c2.f # f is not an attribute of c1 nor c2, thus the lookup 
will try in the class and find C.f
1 1

c1.f = 10 # this create the c1 instance attribute f != class attribute f
c2.f = 20 # this create the c2 instance attribute f != class attribute f

print c1.f, c2.f, c1.g(), c2.g(), C.f
10 20 1 1 1

Cheers,

JM







More information about the Python-list mailing list