[Tutor] How to set variables inside a class()

Alan Gauld alan.gauld at btinternet.com
Tue Nov 26 11:53:27 CET 2013


On 26/11/13 07:30, Reuben wrote:
> Hi,
>
> Following is my code:
> #############################################
> class Animal():
>
>        flag = True
>        print flag
>
>        def __init__(self,name):
> self.name <http://self.name> = name
>             print self.name <http://self.name>
>
>        def walk(self):
>            print "I am walking"
>
>
> if __name__ == '__main__':
>       test = Animal('boxer')
>       test.flag = False


If you really want the flag to be a class attribute rather than an 
instance one you should set it using the class name. So instead of 
test.flag use
         Animal.flag = False

That works inside the class methods too.

By setting test.flag you are creating a new instance level attribute
that exists only within the test instance. That's legal Python
but usually its not a good idea to have different instances of
the same class having different attributes.

 >>> class C:
...    f = True
...    def g(self): self.f = 42
...
 >>> c = C()
 >>> c.f
True
 >>> c.g()
 >>> c.f
42
 >>> C.f
True
 >>> d = C()
 >>> d.f = 66
 >>> d.f
66
 >>> C.f
True
 >>>



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list