Class and Objects
Class and Objects
OBJECTS
PYTHON OBJECTS AND CLASSES
Python is an object-oriented programming language. Unlike procedure-oriented
programming, where the main emphasis is on functions, object-oriented programming
stresses on objects.
An object is a collection of data (variables) and methods (functions) that act on those data.
Similarly, a class is a blueprint for that object.
We can think of a class as a sketch (prototype) of a house. It contains all the details about
the floors, doors, windows, etc. Based on these descriptions, we built the house. House is
the object.
As many houses can be made from a house’s blueprint, we can create many objects from
a class. An object is also called an instance of a class, and the process of creating this
object is called instantiation.
DEFINING A CLASS
Class creates a user-defined data structure, which holds its data members and member functions, which
can be accessed and used by creating an instance of that class.
Classes are created by keyword class.
Class contains:
Attributes: Represented by variables
Actions: Performed on methods
Attributes are always public and can be accessed using the dot (.) operator.
As soon as we define a class, a new class object is created with the same name. This class object allows
us to access the different attributes as well as to instantiate new objects of that class.
Syntax of defining a class:
class classname(object):
“ “ “ Docstrings ” ” ”
Attributes
def__init__(self):
def method1():
def method2():
class Person:
" " " This is a person class " " "
age = 10
def greet(self):
print('Hello')
CLASS EXAMPLE
# Output: 10
print(Person.age)
# Object instantiation
Rodger = Dog()
def add(self):
return self.x + self.y
# Object instantiation
calc = calculator(10,20)
print(calc.add())
CONSTRUCTORS IN PYTHON
Constructors are generally used for instantiating an object.
The task of constructors is to initialize(assign values) to the class data members
when an object of the class is created.
In Python, the __init__() method is called the constructor and is always called when
an object is created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor
Types of constructors :
DEFAULT CONSTRUCTOR: The default constructor is a simple constructor which doesn’t accept any
arguments. Its definition has only one argument: a reference to the constructed instance, known as
the self.
PARAMETERIZED CONSTRUCTOR: constructor with parameters is known as parameterized
constructor. The parameterized constructor takes its first argument as a reference to the instance
being constructed, known as self, and the rest of the arguments are provided by the programmer.
EXAMPLE OF DEFAULT CONSTRUCTOR class con:
# default constructor
Output:
def __init__(self):
self.cc = “python" python
# Initializing
def __init__(self):
print('Employee created.')
Output:
obj = Employee()
del obj Employee created.
It refers to defining a new class with little or no modification to an existing class. The
new class is called the derived (or child) class, and the one it inherits is called the base
(or parent) class.
Derived class inherits features from the base class where new features can be added to
it. This results in the re-usability of code.
Python Inheritance Syntax:
class BaseClass:
{Body}
class DerivedClass(BaseClass):
{Body}
class Person: EXAMPLE
# Constructor
def __init__(self, name): If an attribute is not found in the class itself, the search
self.name = name continues to the base class. This repeats recursively
# To get name if the base class is itself derived from other
def getName(self): classes.
return self.name
# To check if this person is an employee
def isEmployee(self):
return False
# Inherited or Subclass (Note Person in bracket)
class Employee(Person):
# Here we return true
def isEmployee(self):
return True
# An Object of Person
emp = Person(“Satyam")
print(emp.getName(), emp.isEmployee()) Output:
# An Object of Employee
emp = Employee(“Mayank") Satyam False
print(emp.getName(), emp.isEmployee())
Mayank True
METHOD OVERRIDING IN PYTHON
▪ A child class needs to identify which class is its parent class. This can be done by
mentioning the parent class name in the definition of the child class.
▪ If suppose __init__() method was defined in both classes, Person as well Employee. When
this happens, the method in the derived class overrides that in the base class. This is to say,
__init__() in Employee gets preference over the __init__() in Person.
▪ Generally, when overriding a base method, we tend to extend the definition rather than
replace it.
▪ The same is being done by calling the method in the base class from the one in the derived
class (calling Person.__init__() from __init__() in Employee).
▪Syntax:
parent_class_name.method_name_of_parent_class()
# parent class
class Person(object):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
self.name = name Output:
self.idnumber = idnumber
EXAMPLE
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)
Output:
inherited by the child class, i.e. we can make some of the instance
variables of the parent class private, which won’t be available to the child
class.
class D(C):
def __init__(self): File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py",
self.e = 84 line 16, in
C.__init__(self) print (object1.d)
AttributeError: type object 'D' has no attribute 'd'
object1 = D()
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
Output:
# Driver's code
object = Child() This function is in parent class.
object.func1()
object.func2() This function is in child class.
MULTIPLE INHERITANCE
▪When a class can be derived
from more than one base class
this type of inheritance is
called multiple inheritances.
print(self.mothername)
# Base class2
class Father:
Output:
fathername = ""
EXAMPLE
# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername): Father name : Ram
self.sonname = sonname
# invoking constructor of Father class
Father.__init__(self, fathername, grandfathername) Son name : Kush
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son(‘Kush', 'Ram', ‘Dashrath')
print(s1.grandfathername)
s1.print_name()
HIERARCHICAL INHERITANCE
When more than one
derived class are created
from a single base this type
of inheritance is called
hierarchical inheritance.
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
EXAMPLE
Output:
# Derivied class2
class Child2(Parent): This function is in parent class.
def func3(self):
print("This function is in child 2.")
This function is in child 1.
# Driver's code
object1 = Child1()
This function is in parent class.
object2 = Child2()
object1.func1() This function is in child 2.
object1.func2()
object2.func1()
object2.func3()
HYBRID INHERITANCE
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
EXAMPLE
class Student2(School):
def func3(self):
print("This function is in student 2.") Output:
# Driver's code
object = Student3()
object.func1()
object.func2()
ENCAPSULATION IN PYTHON
▪Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP).
▪ Encapsulation describes the idea of wrapping data and the methods that work
on data within one unit.
▪This puts restrictions on accessing variables and methods directly and can
prevent the accidental modification of data.
▪To prevent accidental change, an object’s variable can only be changed by an
object’s method. Those types of variables are known as private variables.
▪A class is an example of encapsulation as it encapsulates all the data:
member functions, variables, etc.
▪The goal of information hiding is to ensure that an object’s state is always
valid by controlling access to attributes that are hidden from the outside world.
PROTECTED MEMBERS
▪Protected members are those members of the class that cannot be accessed
outside the class but can be accessed from within the class and its subclasses.
▪To accomplish this in Python, just follow the convention by prefixing the
member’s name with a single underscore “_”.
▪Although the protected variable can be accessed out of the class as well as
in the derived class (modified too in the derived class), it is
customary(convention not a rule) to not access the protected out the class
body.
Output:
# Creating a base class
class Base:
Calling protected member of base class: 2
def __init__(self):
# Protected member Calling modified protected member outside class: 3
self._a = 2
# Creating a derived class Accessing protected member of obj1: 3
class Derived(Base):
EXAMPLE
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
print(obj1.c)
obj2 = Derived()
# Creating a Base class
class Base: Output:
def __init__(self):
self.a = “Python" Python
self.__c = “Programming” Programming
# Driver code
obj1 = Base()
print(obj1.a)
obj1.display()
obj2 = Derived()
POLYMORPHISM IN PYTHON
▪The word polymorphism means having many forms.
▪In programming, polymorphism means the same function name (but different
signatures) being used for different types.
▪The key difference is the data types and number of arguments used in the
function.
# Python program to demonstrate in-built functions # A simple Python function to demonstrate
# Polymorphism
▪In inheritance, the child class inherits the methods from the parent class. However,
it is possible to modify a method in a child class that it has inherited from the
parent class.
▪This is particularly useful in cases where the method inherited from the parent
class doesn’t quite fit the child class.
▪In such cases, we re-implement the method in the child class. This process of re-
implementing a method in the child class is known as Method Overriding
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
EXAMPLE