Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python class variable

class Foo:
    num_of_foos = 0     # class variable, shared by all instances
    raise_amt = 1.04    # class variable
    def __init__(self, x):
        self.instance_var = x
        Foo.num_of_foos += 1    # class safe way to use class variable
    def raise_me(self):
        # self.raise_amt allows object / subclass to override class variable
        return self.instance_var * self.raise_amt   

bar = Foo(1)
baz = Foo(1)
Foo.num_of_foos     # 2
bar.num_of_foos     # 2
bar.raise_me()      # 1.04
bar.raise_amt = 1.5 # create instance variable that overrides class variable
bar.raise_me()      # 1.5
 
PREVIOUS NEXT
Tagged: #python #class #variable
ADD COMMENT
Topic
Name
9+9 =