# Class variables refer to variables that are made within a class.
# It is generated when you define the class.
# It's shared with all the instance of that class.
# Example:
class some_variable_holder(object):
var = "This variable is created inside the class some_variable_holder()."
def somefunc(self):
print("Random function ran.")
thing = some_variable_holder()
another_thing = some_variable_holder()
# Both does the same thing because the same variable has been passed on from the class.
thing.var
another_thing.var
class Shark:
animal_type = "fish"
location = "ocean"
followers = 5
new_shark = Shark()
print(new_shark.animal_type)
print(new_shark.location)
print(new_shark.followers)
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
// no need to define variables explicitly like in java or c++
// we need to define them in __init__ method that creates, this i8s the key
// __init__ basically it's constructor
// instance variables for the current object self( which denotes your created instance)
class A:
def __init__(self,d):
self.d=d
//above automaticaaly creates an instance variable d for you class object
hence
ob=A(4)
// creates object ob with 1 instance variable d initialised to 4
ALSO NOTE:
// in python there is no distinction between pointer variable and
// normal variable we use same syntax for both unlike c++
// so how python distinguishes b/w a reference and normal var?
// by seeing what is being assigned to it on RHS