0% found this document useful (0 votes)
2 views

Module 12

The document outlines the principles of object-oriented programming (OOP) in Python, covering classes, instances, inheritance, and method overriding. It explains key concepts such as class variables, instance variables, method definitions, and operator overloading, along with examples of creating and using classes. Additionally, it discusses data hiding, class methods, and the destruction of objects through garbage collection.

Uploaded by

ahad siddiqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 12

The document outlines the principles of object-oriented programming (OOP) in Python, covering classes, instances, inheritance, and method overriding. It explains key concepts such as class variables, instance variables, method definitions, and operator overloading, along with examples of creating and using classes. Additionally, it discusses data hiding, class methods, and the destruction of objects through garbage collection.

Uploaded by

ahad siddiqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Classes

• mixture of C++ and Module -3


• multiple base classes
• derived class can override any methods of its base class(es)
• method can call the method of a base class with the same name
• objects have private data
• C++ terms:
– all class members are public
– all member functions are virtual
– no destructors (not needed)
• classes (and data types) are objects
• built-in types cannot be used as base classes by user
• arithmetic operators, subscripting can be redefined for class instances (like C++, unlike
Java)

1
© Nex-G Exuberant Solutions Pvt. Ltd.
OOP Terminology

• Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables
and instance variables) and methods, accessed via dot notation.
• Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables aren't
used as frequently as instance variables are.
• Data member: A class variable or instance variable that holds data associated with a
class and its objects.
• Function overloading: The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects (arguments) involved.
• Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
• Inheritance : The transfer of the characteristics of a class to other classes that are
derived from it. .

2
© Nex-G Exuberant Solutions Pvt. Ltd.
OOP Terminology

• Instance: An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
• Instantiation : The creation of an instance of a class.
• Method : A special kind of function that is defined in a class definition.
• Object : A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
• Operator overloading: The assignment of more than one function to a particular
operator

3
© Nex-G Exuberant Solutions Pvt. Ltd.
What is a Class?
• Data structures like lists and strings are extremely useful, but sometimes they aren’t
enough to represent something you’re trying to implement
• Classes give us the ability to create more complicated data structures that contain
arbitrary content. We can create a Pet class that keeps track of the name and species of
the pet in usefully named attributes called name and species, respectively.

What is an Instance?
• Before we get into creating a class itself, we need to understand an important distinction.
A class is something that just contains structure – it defines how something should be laid
out or structured, but doesn’t actually fill in the content. For example, a Pet class may say
that a pet needs to have a name and a species, but it will not actually say what the pet’s
name or species is.
• This is where instances come in. An instance is a specific copy of the class that does
contain all of the content

4
© Nex-G Exuberant Solutions Pvt. Ltd.
Creating Classes

• The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows−
• Note: By convention class names are always capitalized.

class ClassName:
'Optional class documentation string'
pass # Pass keyword as a placeholder for body of class

• The class has a documentation string, which can be accessed via ClassName.__doc__
• The body consists of all the component statements defining class members, data
attributes and functions

5
© Nex-G Exuberant Solutions Pvt. Ltd.
Ex-
class Employee:
'Common base class for all employees'
# Class variables
empCount = 0
def __init__(self, name, salary):
# Instance variables
self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print(f"Total Employee {Employee.empCount}")

def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
6
© Nex-G Exuberant Solutions Pvt. Ltd.
• The variable empCount is a class variable whose value would be shared among all
instances of a this class.
• This can be accessed as Employee.empCount from inside the class or outside the
class.
• The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
• You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you
don't need to include it when you call the methods.

7
© Nex-G Exuberant Solutions Pvt. Ltd.
Creating instance objects:
To create instances of a class, you call the class using class name and pass in whatever
arguments
its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

Accessing attributes:
You access the object's attributes using the dot operator with object. Class variable would
be accessed using class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print(f"Total Employee {Employee.empCount}”)

8
© Nex-G Exuberant Solutions Pvt. Ltd.
Example
•Now, putting all the concepts together −
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print(f"Total Employee {Employee.empCount}”)

When the above code is executed, it produces the following result −


Name : Zara, Salary: 2000
Name : Manni, Salary: 5000
Total Employee 2

9
© Nex-G Exuberant Solutions Pvt. Ltd.
Namespaces

• scope = textual region of Python program where a namespace is directly accessible


(without dot)
– innermost scope (first) = local names
– middle scope = current module's global names
– outermost scope (last) = built-in names
• assignments always affect innermost scope
– don't copy, just create name bindings to objects
• global indicates name is in global scope

Apr 10, 2025 10


© Nex-G Exuberant Solutions Pvt. Ltd.
Class objects

• obj.name references (plus module!):


class MyClass:
"A simple example class"
i = 123
def f(self):
return 'hello world'
>>> MyClass.i
123
• MyClass.f is method object

© Nex-G Exuberant Solutions Pvt. Ltd.


Class objects

• class instantiation:
>>> x = MyClass()
>>> print(x.f())
'hello world'
• creates new instance of class
– note x = MyClass vs. x = MyClass()
• ___init__() special method for initialization of object
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart

© Nex-G Exuberant Solutions Pvt. Ltd.


Instance objects

• attribute references
• data attributes (C++/Java data members)
– created dynamically
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter

Apr 10, 2025 13


© Nex-G Exuberant Solutions Pvt. Ltd.
Method objects

• Called immediately:
x.f()
• can be referenced:
xf = x.f
while True:
print xf()
• object is passed as first argument of function _ 'self'_
– x.f() is equivalent to MyClass.f(x)

Apr 10, 2025 14


© Nex-G Exuberant Solutions Pvt. Ltd.
Notes on classes

• Data attributes override method attributes with the same name


• no real hiding  not usable to implement pure abstract data types
• clients (users) of an object can add data attributes
• first argument of method usually called self
– 'self' has no special meaning (cf. Java)

Apr 10, 2025 15


© Nex-G Exuberant Solutions Pvt. Ltd.
Built--‐In Class Attributes:

• Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute:
• __dict__ : Dictionary containing the class's namespace.
• __doc__ : Class documentation string or None if undefined.
• __name__: Class name.
• __module__: Module name in which the class is defined. This attribute is "__main__"
in interactive mode.
• __bases__ : A possibly empty tuple containing the base classes, in the order of their
occurrence in the base class list.

16
© Nex-G Exuberant Solutions Pvt. Ltd.
Destroying Objects (Garbage Collection):

• Python deletes unneeded objects (built-in types or class instances) automatically to free
memory space.
• An object's reference count increases when it's assigned a new name or placed in a
container (list, tuple or dictionary). The object's reference count decreases when it's
deleted with del, its reference is reassigned, or its reference goes out of scope. When an
object's reference count reaches zero, Python collects it automatically.
• when the garbage collector destroys an orphaned instance and reclaims its space. But a
class can implement the special method __del__(), called a destructor, that is invoked
when the instance is about to be destroyed. This method might be used to clean up any
non memory resources used by an instance.

a = 40 # Create object <40>


b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>

17
© Nex-G Exuberant Solutions Pvt. Ltd.
EXAMPLE:

This __del__() destructor prints the class name of an instance that is about to be destroyed:
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, “ destroyed“)
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # prints the ids of the objects
del pt1
del pt2
del pt3 When the above code is executed, it produces the
following result:
3083401324 3083401324 3083401324
Point destroyed
18
© Nex-G Exuberant Solutions Pvt. Ltd.
Class Inheritance

Instead of starting from scratch, you can create a class by deriving it from a pre existing
class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes
as if they were defined in the child class. A child class can also override data members and
methods from the parent.
SYNTAX:
Derived classes are declared much like their parent class; however, a list of base classes
to inherit from are given after the class name:
class SubClassName (ParentClass1, ParentClass2, ...):
'Optional class documentation string’
pass

19
© Nex-G Exuberant Solutions Pvt. Ltd.
EXAMPLE

class Parent: # define parent class


parentAttr = 100
def __init__(self):
print("Calling parent constructor“)
def parentMethod(self):
print('Calling parent method’)
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attribute :", Parent.parentAttr)
class Child(Parent): # define child class
def __init__(self):
print("Calling child constructor“)
def childMethod(self):
print('Calling child method’)

20
© Nex-G Exuberant Solutions Pvt. Ltd.
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

When the above code is executed, it produces the following result:


Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

21
© Nex-G Exuberant Solutions Pvt. Ltd.
Overriding Methods:

You can always override your parent class methods. One reason for overriding parent's
methods is because you may want special or different functionality in your subclass.
EXAMPLE:
class Parent: # define parent class
def myMethod(self):
print('Calling parent method’)
class Child(Parent): # define child class
def myMethod(self):
print('Calling child method’)
c = Child() # instance of child
c.myMethod() # child calls overridden method

When the above code is executed, it produces the following result:


Calling child method

22
© Nex-G Exuberant Solutions Pvt. Ltd.
Overloading Operators

Suppose you've created a Vector class to represent two-dimensional vectors, what


happens when you use the plus operator to add them? You could, however, define the
__add__ method in your class to perform vector addition and then the plus operator would
behave as per expectation:
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return(f'Vector {self.a}, {self.b}’)
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print(v1 + v2)
When the above code is executed, it produces the following result:
Vector(7,8)

23
© Nex-G Exuberant Solutions Pvt. Ltd.
Data Hiding:

An object's attributes may or may not be visible outside the class definition. For these cases, you
can name attributes with a double underscore prefix, and those attributes will not be directly visible
to outsiders.
EXAMPLE:
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.__secretCount)
When the above code is executed, it produces Attribute error

24
© Nex-G Exuberant Solutions Pvt. Ltd.
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName. If you would replace
your last line as following, then it would work for you:
print(counter._JustCounter__secretCount)

When the above code is executed, it produces the following result:


1
2
2

25
© Nex-G Exuberant Solutions Pvt. Ltd.
Class Methods

• It is a special type of method that is bound to the class instead of the instance of the
class
• Class methods can access all attributes that are bound to the class itself. E.g., class
variables, other class methods and static methods.
• To define a class method, we use the decorator @classmethod. And like the ‘self’
keyword in normal methods, we use ‘cls’ keyword for class methods.
• On the next slide is an example using the employee class from before:

26
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025
Class Methods

class Employee:
'Common base class for all employees'
# Class variables
empCount = 0
def __init__(self, name, salary):
# Instance variables
self.name = name
self.salary = salary
Employee.empCount += 1

@classmethod
def displayCount(cls):
print(f"Total Employee {cls.empCount}")

def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
27
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025
Static Methods

• It is a special type of method that is similar to a normal function and not bound to the
class or instance at all.
• Static methods cannot access any class attributes or methods.
• To define a static method, we use the decorator @staticmethod. We don’t need to define
‘self’ or ‘cls’ for a static method.
• On the next slide is an example using the employee class from before:

28
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025
Static Methods

class Employee:
'Common base class for all employees'
# Class variables
empCount = 0
def __init__(self, name, salary):
# Instance variables
self.name = name
self.salary = salary
Employee.empCount += 1

@classmethod
def displayCount(cls):
print(f"Total Employee {cls.empCount}")

@staticmethod
def sum(num1, num2):
return num1 + num2

29
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025

You might also like