Class is a user defined datatype in which it consists of functions and data variables. Classes can be accessed by creating a object which is the instance of the class.
class className(parentClass):
This is the syntax for the class. By default, object is the parent class for all the classes.
Functions Inside Class
Functions can be declared inside the class by using a keyword self which is similar to this pointer. Function which is declared inside the class should have a arguement as a self.
class myFirstClass(object):
def set(self, name):
self.name = name
Creating Objects
For the above class, the object can be created by simply assigning the object name with the class name.
p = myFirstClass()
p.set(“Chandru”)
Constructor
Constructor is used to initialize a variable of the class. __init__() function is used to initialize the variable. Constructor is automatically invoked when a object is created.
class constructor(object):
def __init__(self):
print(“Object is created”)
Inheritance
Inheritance is the property of acquiring the base class property. In simple it is also defined as deriving the property of one class into another class. For deriving the properties of base class, the name of the class which has to be derived in the derived class has to be passed as the arguement.
class base(object):
def __init__(self):
print(“Base class”)
class derived(base):
def __init__(self):
print(“Derived class”)
d = derived()
Output:-
Base class
Derived class
Multiple Inheritance
This can be achieved by passing the multiple classes in which the properties of these classes has to be derived to the class as arguement.
class multiple(baseClass1, baseClass2):
Setters and Getters
class setAndGet(object):
def __init__(self, name):
self.name = name
p = setAndGet(“Chandru”)
print(p.name)
p,name = “Python”
print(p.name)
Output:-
Chandru
Python