A Few Notes About Python Static Class Member

class Vertebra(object):
    weight = 0.1
    def __init__(self):
        print 'init vertebra'
                
class Fish(Vertebra):
    def __init__(self):
        super(Fish, self).__init__()
        print 'init fish'
        
class Bird(Vertebra):
    def __init__(self):
        super(Bird, self).__init__()
        print 'init bird'
        
class Kingfisher(Bird):
    def __init__(self):
        super(Kingfisher, self).__init__()
        print 'init kingfisher'

Any variable placed right after the class definition will be kinda static. Access the variable by <Class>.<Variable>, i.e.

Vertebra.weight

Any derived class will its <Class>.<Variable>, inherited from its parent class until it has been set specifically. i.e.

Fish.weight
Bird.weight
Kingfisher.weight

Any instance of the class will have a variable of its own, <Instance>.<Variable>, which equals to the value of <Class>.<Variable> until it has been set specifically.

tuna = Fish()
tuna.weight

Any changes to <Class>.<Variable> will affect all relevant variables of all derived classes.

Vertebra.weight = 99.0
Kingfisher.weight

Any changes to <Class>.<Variable> will only affect the values of <Instance>.<Variable> of all existing instances of the class and derived classes, except those have been set specifically.

sootyTern = Bird()
yellowBill = Kingfisher()
sootyTern.weight()
yellowBill.weight()
Bird.weight = 39.1
sootyTern.weight()
yellowBill.weight()

Set value to <Class>.<Variable> will liberate it from changes of inherited class.i.e.

Fish.weight = 1405.9
Vertebra.weight = 0.74
Fish.weight

Set value to <Instance>.<Variable> will liberate it from changes of instanced class and inherited class.i.e.

yellowBill.weight = 463.3
Bird.weight = 239.1
yellowBill.weight

 

Advertisements

Leave a comment

Filed under Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s