Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Class and Objects

The document provides an overview of Python's object-oriented programming concepts, including classes, objects, inheritance, and methods. It explains the definitions and functionalities of classes and objects, the use of constructors and destructors, and various types of inheritance such as single, multiple, multilevel, and hierarchical inheritance. Additionally, it covers the importance of the 'self' variable and method overriding in Python.

Uploaded by

nobili4371
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Class and Objects

The document provides an overview of Python's object-oriented programming concepts, including classes, objects, inheritance, and methods. It explains the definitions and functionalities of classes and objects, the use of constructors and destructors, and various types of inheritance such as single, multiple, multilevel, and hierarchical inheritance. Additionally, it covers the importance of the 'self' variable and method overriding in Python.

Uploaded by

nobili4371
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

PYTHON CLASS AND

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)

# Output: <function Person.greet>


print(Person.greet)

# Output: "This is a person class"


print(Person.__doc__)
CREATING AN OBJECT IN PYTHON
An Object is an instance of a Class.
A class is like a blueprint, while an instance is a copy of the class with actual values.
An object consists of :
 State: It is represented by the attributes of an object. It also reflects the properties of an
object.
 Behaviour: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.
When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behaviour of the class. But the values of those
attributes, i.e., the state, are unique for each object. A single class may have any number of
instances.
Syntax of creation of an object:
obj = ClassName()
class Dog:
# A simple class Output:
# attribute
Breed = "Labrador" Labrador
Color = “golden yellow"
I'm Labrador
EXAMPLE

# A sample method and color is golden yellow


def fun(self):
print("I'm", self.Breed)
print(“and color is ", self.Color)

# Object instantiation
Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.Breed)
Rodger.fun()
THE SELF VARIABLE
Class methods must have an extra first parameter in the method definition. We do not give a value for
this parameter when we call the method; Python provides it.
If we have a method that takes no arguments, we still have one argument.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted
by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about (whenever
an object calls its method, the object itself is passed as the first argument).
Self is the default variable that contains the memory address of the instance of the current class.

S1=student( ) S1 contains the memory address of the instance


This memory is internally and by default passed to the ‘self’ variable
Usage 1
def __init__(self): The ‘self’ variable is used as the first parameter in the constructor
Usage 2
def putdata(self): The ‘self’ variable is used as the first parameter in the instance method
class calculator():
Counter = 0
Output:
def __init__(self, x = 0, y = 0):
30
self.x = x
self.y = y
EXAMPLE

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

# a method for printing data members


def print_cc(self):
print(self.cc)

# creating an object of the class


obj = con()
# calling the instance method using the object obj
obj.print_cc()
EXAMPLE OF PARAMETERIZED CONSTRUCTOR class Addition: Output:
first = 0
second = 0
answer = 0
First number = 1000
Second number = 2000
# parameterized constructor
Addition of two numbers = 3000
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
# creating an object of the class; this will invoke the parameterized constructor
obj = Addition(1000, 2000)
obj.calculate()
obj.display()
DESTRUCTORS IN PYTHON
Destructors are called when an object gets destroyed.
In Python, destructors are not needed as much as in C++ because Python has a garbage
collector that handles memory management automatically.
The __del__() method is known as a destructor method in Python. It is called when all
references to the object have been deleted, i.e., when an object is a garbage collected.
Syntax of destructor declaration :
def __del__(self):
# body of destructor
Any attribute of an object can be deleted anytime, using the del statement.
>>> obj = Addition(1000, 2000)
Example: >>> del obj.first
>>> obj.calculate()
Traceback (most recent call last):
...
AttributeError: ‘Addition' object has no attribute ‘first’
>>> del Addition.calculate
>>> obj.calculate()
Traceback (most recent call last):
...
AttributeError: ‘Addition' object has no attribute ‘calculate'
EXAMPLE DESTRUCTORS By using the del keyword, we
deleted all references of object
# Python program to illustrate destructor ‘obj’; therefore, destructor was
class Employee:
invoked automatically.

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

Output:
obj = Employee()
del obj Employee created.

Destructor called, Employee deleted.


class Employee: EXAMPLE DESTRUCTORS
# Initializing
def __init__(self): The destructor was called after the
print('Employee created') program ended, when object went out of
scope.
# Calling destructor
def __del__(self):
print("Destructor called")
Output:

def Create_obj(): Calling Create_obj() function...


print('Making Object...')
obj = Employee() Making Object...
print('function end...') Employee created
return obj
function end...
Program End...
print('Calling Create_obj() function...')
obj = Create_obj() Destructor called
print('Program End...')
INHERITANCE IN PYTHON
Inheritance is a powerful feature in object-oriented programming.

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

def display(self): Rahul


print(self.name)
886012
print(self.idnumber)

# 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)

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")
# calling a function of the class Person using its instance
a.display()
class A:
def __init__(self, n='Rahul'):
self.name = n If you forget to invoke the __init__()
of the parent class, then its instance
class B(A): variables will not be available to
EXAMPLE

def __init__(self, roll): the child class. Then it will raise an


self.roll = roll
Attribute Error.
object = B(23)
print(object.name)

Output:

Traceback (most recent call last):


File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in
print (object.name)
AttributeError: 'B' object has no attribute 'name'
PRIVATE MEMBERS OF THE PARENT CLASS
▪ We don’t always want the instance variables of the parent class to be

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.

▪We can make an instance variable private by adding double underscores

before its name.


class C(object):
def __init__(self):
self.c = 21

# d is private instance variable


self.__d = 42
Output:
EXAMPLE

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()

# produces an error as d is a private instance variable


print(object1.d)
TYPES OF INHERITANCE
SINGLE INHERITANCE
Single inheritance enables a
derived class to inherit
properties from a single
parent class, thus enabling
code reusability and adding
new features to existing
code.
EXAMPLE
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# 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.

▪In multiple inheritances, all


the features of the base
classes are inherited into the
derived class.
# Base class1
class Mother:
mothername = ""
def mother(self):

print(self.mothername)
# Base class2
class Father:
Output:
fathername = ""
EXAMPLE

def father(self): Father : RAM


print(self.fathername)
# Derived class Mother : SITA
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
MULTILEVEL INHERITANCE
In multilevel inheritance,
features of the base class and
the derived class are further
inherited into the new derived
class. This is similar to a
relationship representing a
child and a grandfather.
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername

# Intermediate class Output:


class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername Dashrath
# invoking constructor of Grandfather class
Grandfather.__init__(self, grandfathername)
Grandfather name : Dashrath
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:

class Student3(Student1, School): This function is in school.


def func4(self):
print("This function is in student 3.")
This function is in student 1.

# 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

def __init__(self): Accessing protected member of obj2: 2


# Calling constructor of Base class
Base.__init__(self)
print("Calling protected member of base class: ", self._a)
# Modify the protected variable:
self._a = 3
print("Calling modified protected member outside class: ", self._a)
obj1 = Derived()
obj2 = Base()
# Calling protected member
# Can be accessed but should not be done due to convention
print("Accessing a protected member of obj1: ", obj1._a)
# Accessing the protected variable outside
print("Accessing protected member of obj2: ", obj2._a)
PRIVATE MEMBERS
▪Private members are similar to protected members, the
difference is that the class members declared private should
neither be accessed outside the class nor by any base class;

▪ it can be accessed by the method of that class only.

▪However, to define a private member, prefix the member's


name with the double underscore “__”.
Output:
# Creating a Base class
class Base: Python
def __init__(self): Traceback (most recent call last):
self.a = “Python" File "/home/f4905b43bfcf29567e360c709d3c52bd.py", line 25, in <module>
self.__c = “Programming" print(obj1.c)
AttributeError: 'Base' object has no attribute 'c’

Traceback (most recent call last):


# Creating a derived class File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 27, in <module>
EXAMPLE

class Derived(Base): obj2 = Derived()


def __init__(self): File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 20, in __init__
print(self.__c)
AttributeError: 'Derived' object has no attribute '_Derived__c'

# 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

def display(self): Traceback (most recent call last):


File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 27, in <module>
print(self.__c)
obj2 = Derived()
File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 20, in __init__
EXAMPLE

# Creating a derived class print(self.__c)


class Derived(Base): AttributeError: 'Derived' object has no attribute '_Derived__c'
def __init__(self):
# 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)
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

# len() being used for a string


print(len(“Python")) def add(x, y, z = 0):
return x + y+z

# len() being used for a list


print(len([10, 20, 30])) # Driver code
print(add(2, 3))
print(add(2, 3, 4))
POLYMORPHISM WITH INHERITANCE
▪In Python, Polymorphism lets us define methods in the child class that have the
same name as the methods in the parent class.

▪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

print("Sparrows can fly.")


Output:
class ostrich(Bird):
There are many types of birds.
def flight(self):
print("Ostriches cannot fly.")
Most of the birds can fly but some cannot.
obj_bird = Bird()
There are many types of birds.
obj_spr = sparrow()
obj_ost = ostrich()
Sparrows can fly.
obj_bird.intro()
obj_bird.flight()
There are many types of birds.
obj_spr.intro()
obj_spr.flight()
Ostriches cannot fly.
obj_ost.intro()
obj_ost.flight()

You might also like