Classes In Python
June 25, 2017
Categorised in: Python
Quick overview of the syntax of class in python.
- Simple form:
class NameOfClass:
attributes
.
.
.
- More wholesome form:
class ClassExample:
"""Documentation part """
attribute = "Class Variable" # class varirable which is shared by all its instances
def function(self): # self == object/instance
return "Function called"
def __init__(self, instance_var): # Constructor like. No return statement. Only initialization
self.inst_var = instance_var # unique to each instance
obj = ClassExample("Instance Variable")
print(
obj.attribute,
"\n"+obj.inst_var,
"\n"+obj.function(),
"\n"+obj.__doc__
)
OUTPUT
Class Variable
Instance Variable
Function called
Documentation part
- Inheritance concept is also included in Python.
class Base:
some_list = [] # common to every instance
def __init__(self, name):
self.name = name # particular to each instance
class DerivedClass(Base):
def update_list(self, something):
self.some_list.append(something)
baseObj = Base("First Base")
'''
derived class object has to fulfill __init__
argument requirement since it does not implement
its own __init__
'''
deriveObj = DerivedClass("First Derive") # name is particular to each instance
print(deriveObj.some_list) # derived object has inherited properties & behaviors of base
deriveObj.update_list("item1")
print(deriveObj.name)
print(baseObj.name)
print(baseObj.some_list)
print(deriveObj.some_list)
'''
MULTIPLE INHERITANCE:
class DeriveMultiple( Base1, Base2, ..., Basen ):
.
.
.
'''
OUTPUT:
[]
First Derive
First Base
[‘item1’]
[‘item1’]
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.