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

Steven D'Aprano steve at pearwood.info
Tue Nov 26 13:12:58 CET 2013


On Tue, Nov 26, 2013 at 01:00:18PM +0530, Reuben wrote:
> Hi,
> 
> Following is my code:
> #############################################
> class Animal():
> 
>       flag = True
>       print flag

This "flag" is a class attribute, which means it is shared by all 
instances. Every Animal will see the same flag. (Unless you set a new 
one on the individual animal.)

>       def __init__(self,name):
>            self.name = name
>            print self.name

This "name" is an instance attribute, which means it is not shared.

>       def walk(self):
>           print "I am walking"
> 
> 
> if __name__ == '__main__':
>      test = Animal('boxer')
>      test.flag = False
>      test.walk()

The line test.flag creates a new instance attribute on that specific 
Animal, which shadows (hides) the class attribute.


> My question is:
> ____________
> 
> 1)Inside the Animal class(), How can I set the variable 'flag' to FALSE?

The same way you set it to true, only use False instead.

class Animal():
    flag = False

If you want it specific to the individual instead of shared, put it 
inside the __init__ method, using self:

class Animal():
    def __init__(self,name):
        self.name = name
        self.flag = False




-- 
Steven


More information about the Tutor mailing list