SlideShare a Scribd company logo
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
Object Oriented Programming with Python
(Lecture # 01)
by
Muhammad Haroon
1. Object Oriented Programming
Object Oriented Programming (OOP) is a programming technique is which programs are written on the
basis of objects. An object is a collection of data and function. Object may represent a person, thing or
place in real world. In OOP, data and all possible functions on data are grouped together. Object
oriented programs are easier to learn and modify.
Object Oriented Programming is a powerful technique to develop software. It is used to analyze and
design the applications in terms of objects. It deals with data and the procedures that process the data as
a single object.
Some of the object oriented languages that have developed are:
✓ Python
✓ C++
✓ Smalltalk
✓ Eiffel
✓ CLOS
✓ Java
✓ C#
1.1 Features of Object-Oriented Programming
Following are some features of object oriented programming:
✓ Objects
✓ Classes
✓ Class variable
✓ Encapsulation/ Information Hiding
✓ Polymorphism
✓ Inheritance
✓ Overloading
✓ Overriding
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
✓ Abstraction
✓ Real world Modeling
✓ Reusability
Objects
OOP provides the facility of programming based on objects. Object is an entity that consists of data and
functions.
Classes
Classes are designs for creating objects. OOP provides the facility to design classes for creating different
objects. All properties and functions of an object are specified in classes.
Classes 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 are not 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 or 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.
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.
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
Method
A special kind of function that is defined in a class definition.
Operator overloading
The assignment of more than one function to a particular operator.
Real world Modeling
OOP is based on real world modeling. As in real world, things have properties and working capabilities.
Similarly, objects have data and functions. Data represents properties and functions represent working of
objects.
Reusability
OOP provides ways of reusing the data and code. Inheritance is a technique that allows a programmer to
use the code of existing program to create new programs.
Information Hiding
OOP allows the programmer to hide important data from the user. It is performed by encapsulation.
Polymorphism
Polymorphism is an ability of an object to behave in multiple ways.
Objects
An object represents an entity in the real world such as a person, thing or concept etc. An object is
identified by its name. An object consists of the following two things:
✓ Properties: Properties are the characteristics of an object.
✓ Functions: Functions are the action that can be performed by an object.
Examples
Some examples of objects of different types are as follows:
✓ Physical Objects
o Vehicles such as car, bus, truck etc.
o Electrical Components
✓ Elements of Computer User Environment
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
o Windows
o Menus
o Graphics objects
o Mouse and Keyboard
✓ User-defined Data Types
o Time
o Angles
Properties of Object
The characteristics of an objects are known as its properties or attributes. Each object has its own
properties. These properties can be used to describe the object. For example, the properties of an object
Person can be as follows:
✓ Name
✓ Age
✓ Weight
The properties of an object Car can be as follows:
✓ Color
✓ Price
✓ Model Engine
✓ Engine Power
The set of values of the attributes of a particular object is called its state. It means that the state of an
object can be determined by the values of its attributes. The following figure shows the values of the
attributes of an object Car:
Car
Model Honda City
Color Silver
Price 1200000
Engine Power 1600CC
Table 1.1: Properties of an object Car
Function of Object
An object can perform different tasks and actions. The actions that can be performed by an object are
known as functions or methods. For example, the object Car can perform the following functions:
✓ Start
✓ Stop
✓ Accelerate
✓ Reverse
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
The set of all functions of an object represents the behavior of the object. It means that the overall
behavior of an object can be determined by the list of functions of that object.
Car
Start
Stop
Accelerate
Reverse
Table 2.1: Functions of an object Car
Classes
A collection of objects with same properties and functions is known as class. A class is used to define
the characteristics of the objects. It is used as model for creating different objects of same type. For
example, a class Person can be used to define the characteristics and functions of a person. It can be
used to create many object of type person such as Haroon, Farhan, Jahanzaib, Usman etc. All objects of
Person class will have same characteristics and functions. However, the values of each object can be
different. The values are of the objects are assigned after creating an object.
Each object of a class is known as an instance of its class. For example, Haroon, Farhan and Jahanzaib
are three instances of a class Person. Similarly, myBook and youBook can be two instances of a class
Book.
Declaring a Classes
A class is declared in the same way as a structure is declared. The keyword class is used to declare a
class. A class declaration specifies the variables and functions that are common to all objects of that
class. The variables declared in a class are known as member variable or data members.
Syntax
The syntax of declaring a class is as follows:
class ClassName:
'Optional class documentation string'
class_suite
✓ The class has a documentation string, which can be accessed via ClassName.__doc__.
✓ The class_suite consists of all the component statements defining class members, data attributes
and functions.
Example
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
Below is a simple Python program that creates a class with single method.
class Name:
# A sample method
def fun(self):
print("Hello Haroon")
# Code
obj = Name()
obj.fun()
The self
✓ Class methods must have an extra first parameter in method definition. We do not give a value
for this parameter when we call the method, Python provides it
✓ If we have a method which takes no arguments, then we still have to have one argument – the
self. See fun() in above simple example.
✓ This is similar to this pointer in C++ and this reference in Java.
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.
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is
instantiated. The method is useful to do any initialization you want to do with your object.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, My name is', self.name)
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
p = Person('Muhammad Haroon')
p.say_hi()
Class and Instance Variables/attributes
In the Python language, instance variables are variables whose value is assigned inside a constructor or
method with self.
Class variables are variables whose value is assigned in class.
# Python program to show that the variables with a value
# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
# Class for Computer Science Student
class CSStudent:
# Class Variable
stream = 'cs'
# The init method or constructor
def __init__(self, roll):
# Instance Variable
self.roll = roll
# Objects of CSStudent class
a = CSStudent(1)
b = CSStudent(2)
print(a.stream) # prints "cs"
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
print(b.stream) # prints "cs"
print(a.roll) # prints 1
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cs"
We can define instance variables inside normal methods also.
# Python program to show that we can create
# instance variables inside methods
# Class for Computer Science Student
class CSStudent:
# Class Variable
stream = 'cs'
# The init method or constructor
def __init__(self, roll):
# Instance Variable
self.roll = roll
# Adds an instance variable
def setAddress(self, address):
self.address = address
# Retrieves instance variable
def getAddress(self):
OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE
Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761
return self.address
# Code
a = CSStudent(101)
a.setAddress("Muhammad Haroon, Multan")
print(a.getAddress())
How to create an empty class?
We can create an empty class using pass statement in Python.
# An empty class
class Test:
pass
End

More Related Content

PPTX
OOP concepts -in-Python programming language
PPT
Introduction to Python
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PDF
C++ OOPS Concept
PPTX
Machine Learning With Python | Machine Learning Algorithms | Machine Learning...
PPTX
Python Functions
OOP concepts -in-Python programming language
Introduction to Python
Basic Concepts of OOPs (Object Oriented Programming in Java)
C++ OOPS Concept
Machine Learning With Python | Machine Learning Algorithms | Machine Learning...
Python Functions

What's hot (20)

PPTX
Advanced Python : Static and Class Methods
ODP
Python Modules
PPTX
Error and exception in python
PDF
Function in C
PPTX
Python PPT
PPTX
Python Lambda Function
PPTX
Object oriented programming in python
PDF
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
PPTX
Type casting in java
PPTX
Java GC
PDF
Constructor and Destructor
PDF
ch 2. Python module
PDF
Memory Management C++ (Peeling operator new() and delete())
PPTX
Basics of Object Oriented Programming in Python
PPT
Python ppt
PDF
Zero to Hero - Introduction to Python3
PPTX
PDF
Object oriented approach in python programming
Advanced Python : Static and Class Methods
Python Modules
Error and exception in python
Function in C
Python PPT
Python Lambda Function
Object oriented programming in python
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
Type casting in java
Java GC
Constructor and Destructor
ch 2. Python module
Memory Management C++ (Peeling operator new() and delete())
Basics of Object Oriented Programming in Python
Python ppt
Zero to Hero - Introduction to Python3
Object oriented approach in python programming
Ad

Similar to Lecture 01 - Basic Concept About OOP With Python (20)

PPTX
IPP-M5-C1-Classes _ Objects python -S2.pptx
PDF
Python - object oriented
PPTX
Python-Classes.pptx
PPTX
Python advance
PPTX
Regex,functions, inheritance,class, attribute,overloding
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
PPTX
object oriented porgramming using Java programming
PPTX
Object Oriented Programming Class and Objects
PPTX
Python programming Concepts (Functions, classes and Oops concept
PPTX
software construction and development week 3 Python lists, tuples, dictionari...
PPTX
Introduction to OOP in Python
PDF
introductiontooopinpython-171115114144.pdf
PPTX
Object oriented Programming in Python.pptx
PPSX
OOPS Concepts in Python and Exception Handling
PPTX
Object Oriented Programming.pptx
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
PPTX
classes and objects of python object oriented
PPT
07slide.ppt
IPP-M5-C1-Classes _ Objects python -S2.pptx
Python - object oriented
Python-Classes.pptx
Python advance
Regex,functions, inheritance,class, attribute,overloding
Unit 3-Classes ,Objects and Inheritance.pdf
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
object oriented porgramming using Java programming
Object Oriented Programming Class and Objects
Python programming Concepts (Functions, classes and Oops concept
software construction and development week 3 Python lists, tuples, dictionari...
Introduction to OOP in Python
introductiontooopinpython-171115114144.pdf
Object oriented Programming in Python.pptx
OOPS Concepts in Python and Exception Handling
Object Oriented Programming.pptx
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
classes and objects of python object oriented
07slide.ppt
Ad

More from National College of Business Administration & Economics ( NCBA&E) (20)

PPTX
Lecturre 07 - Chapter 05 - Basic Communications Operations
PDF
Lecture # 02 - OOP with Python Language by Muhammad Haroon
PPTX
Lecture 06 - Chapter 4 - Communications in Networks
PPTX
Lecture 05 - Chapter 3 - Models of parallel computers and interconnections
PDF
Lecture01 Part(B) - Installing Visual Studio Code On All Version Of Windows O...
PDF
Lecture02 - Fundamental Programming with Python Language
PDF
Lecture01 - Fundamental Programming with Python Language
PDF
Lecture 04 (Part 01) - Measure of Location
PPTX
Lecture 04 chapter 2 - Parallel Programming Platforms
PPTX
Lecture 04 Chapter 1 - Introduction to Parallel Computing
PDF
Lecture 03 Part 02 - All Examples of Chapter 02 by Muhammad Haroon
PPTX
Lecture 03 - Chapter 02 - Part 02 - Probability & Statistics by Muhammad Haroon
PDF
Lecture 03 - Synchronous and Asynchronous Communication - Concurrency - Fault...
PPTX
Lecture 03 - Chapter 02 - Part 01 - Probability & Statistics by Muhammad Haroon
PPTX
Lecture 02 - Chapter 01 - Probability & Statistics by Muhammad Haroon
PPTX
Lecture 02 - Chapter 1 (Part 02): Grid/Cloud Computing Systems, Cluster Comp...
PPTX
Lecture 01 - Chapter 1 (Part 01): Some basic concept of Operating System (OS)...
PDF
WHO director-general's opening remarks at the media briefing on covid-19 - 23...
PDF
Course outline of parallel and distributed computing
Lecturre 07 - Chapter 05 - Basic Communications Operations
Lecture # 02 - OOP with Python Language by Muhammad Haroon
Lecture 06 - Chapter 4 - Communications in Networks
Lecture 05 - Chapter 3 - Models of parallel computers and interconnections
Lecture01 Part(B) - Installing Visual Studio Code On All Version Of Windows O...
Lecture02 - Fundamental Programming with Python Language
Lecture01 - Fundamental Programming with Python Language
Lecture 04 (Part 01) - Measure of Location
Lecture 04 chapter 2 - Parallel Programming Platforms
Lecture 04 Chapter 1 - Introduction to Parallel Computing
Lecture 03 Part 02 - All Examples of Chapter 02 by Muhammad Haroon
Lecture 03 - Chapter 02 - Part 02 - Probability & Statistics by Muhammad Haroon
Lecture 03 - Synchronous and Asynchronous Communication - Concurrency - Fault...
Lecture 03 - Chapter 02 - Part 01 - Probability & Statistics by Muhammad Haroon
Lecture 02 - Chapter 01 - Probability & Statistics by Muhammad Haroon
Lecture 02 - Chapter 1 (Part 02): Grid/Cloud Computing Systems, Cluster Comp...
Lecture 01 - Chapter 1 (Part 01): Some basic concept of Operating System (OS)...
WHO director-general's opening remarks at the media briefing on covid-19 - 23...
Course outline of parallel and distributed computing

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Pre independence Education in Inndia.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Business Ethics Teaching Materials for college
PPTX
Cell Structure & Organelles in detailed.
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Institutional Correction lecture only . . .
FourierSeries-QuestionsWithAnswers(Part-A).pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
O7-L3 Supply Chain Operations - ICLT Program
Complications of Minimal Access Surgery at WLH
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Pre independence Education in Inndia.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
TR - Agricultural Crops Production NC III.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
O5-L3 Freight Transport Ops (International) V1.pdf
Final Presentation General Medicine 03-08-2024.pptx
Business Ethics Teaching Materials for college
Cell Structure & Organelles in detailed.
Week 4 Term 3 Study Techniques revisited.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Institutional Correction lecture only . . .

Lecture 01 - Basic Concept About OOP With Python

  • 1. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 Object Oriented Programming with Python (Lecture # 01) by Muhammad Haroon 1. Object Oriented Programming Object Oriented Programming (OOP) is a programming technique is which programs are written on the basis of objects. An object is a collection of data and function. Object may represent a person, thing or place in real world. In OOP, data and all possible functions on data are grouped together. Object oriented programs are easier to learn and modify. Object Oriented Programming is a powerful technique to develop software. It is used to analyze and design the applications in terms of objects. It deals with data and the procedures that process the data as a single object. Some of the object oriented languages that have developed are: ✓ Python ✓ C++ ✓ Smalltalk ✓ Eiffel ✓ CLOS ✓ Java ✓ C# 1.1 Features of Object-Oriented Programming Following are some features of object oriented programming: ✓ Objects ✓ Classes ✓ Class variable ✓ Encapsulation/ Information Hiding ✓ Polymorphism ✓ Inheritance ✓ Overloading ✓ Overriding
  • 2. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 ✓ Abstraction ✓ Real world Modeling ✓ Reusability Objects OOP provides the facility of programming based on objects. Object is an entity that consists of data and functions. Classes Classes are designs for creating objects. OOP provides the facility to design classes for creating different objects. All properties and functions of an object are specified in classes. Classes 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 are not 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 or 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. 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.
  • 3. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 Method A special kind of function that is defined in a class definition. Operator overloading The assignment of more than one function to a particular operator. Real world Modeling OOP is based on real world modeling. As in real world, things have properties and working capabilities. Similarly, objects have data and functions. Data represents properties and functions represent working of objects. Reusability OOP provides ways of reusing the data and code. Inheritance is a technique that allows a programmer to use the code of existing program to create new programs. Information Hiding OOP allows the programmer to hide important data from the user. It is performed by encapsulation. Polymorphism Polymorphism is an ability of an object to behave in multiple ways. Objects An object represents an entity in the real world such as a person, thing or concept etc. An object is identified by its name. An object consists of the following two things: ✓ Properties: Properties are the characteristics of an object. ✓ Functions: Functions are the action that can be performed by an object. Examples Some examples of objects of different types are as follows: ✓ Physical Objects o Vehicles such as car, bus, truck etc. o Electrical Components ✓ Elements of Computer User Environment
  • 4. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 o Windows o Menus o Graphics objects o Mouse and Keyboard ✓ User-defined Data Types o Time o Angles Properties of Object The characteristics of an objects are known as its properties or attributes. Each object has its own properties. These properties can be used to describe the object. For example, the properties of an object Person can be as follows: ✓ Name ✓ Age ✓ Weight The properties of an object Car can be as follows: ✓ Color ✓ Price ✓ Model Engine ✓ Engine Power The set of values of the attributes of a particular object is called its state. It means that the state of an object can be determined by the values of its attributes. The following figure shows the values of the attributes of an object Car: Car Model Honda City Color Silver Price 1200000 Engine Power 1600CC Table 1.1: Properties of an object Car Function of Object An object can perform different tasks and actions. The actions that can be performed by an object are known as functions or methods. For example, the object Car can perform the following functions: ✓ Start ✓ Stop ✓ Accelerate ✓ Reverse
  • 5. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 The set of all functions of an object represents the behavior of the object. It means that the overall behavior of an object can be determined by the list of functions of that object. Car Start Stop Accelerate Reverse Table 2.1: Functions of an object Car Classes A collection of objects with same properties and functions is known as class. A class is used to define the characteristics of the objects. It is used as model for creating different objects of same type. For example, a class Person can be used to define the characteristics and functions of a person. It can be used to create many object of type person such as Haroon, Farhan, Jahanzaib, Usman etc. All objects of Person class will have same characteristics and functions. However, the values of each object can be different. The values are of the objects are assigned after creating an object. Each object of a class is known as an instance of its class. For example, Haroon, Farhan and Jahanzaib are three instances of a class Person. Similarly, myBook and youBook can be two instances of a class Book. Declaring a Classes A class is declared in the same way as a structure is declared. The keyword class is used to declare a class. A class declaration specifies the variables and functions that are common to all objects of that class. The variables declared in a class are known as member variable or data members. Syntax The syntax of declaring a class is as follows: class ClassName: 'Optional class documentation string' class_suite ✓ The class has a documentation string, which can be accessed via ClassName.__doc__. ✓ The class_suite consists of all the component statements defining class members, data attributes and functions. Example
  • 6. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 Below is a simple Python program that creates a class with single method. class Name: # A sample method def fun(self): print("Hello Haroon") # Code obj = Name() obj.fun() The self ✓ Class methods must have an extra first parameter in method definition. We do not give a value for this parameter when we call the method, Python provides it ✓ If we have a method which takes no arguments, then we still have to have one argument – the self. See fun() in above simple example. ✓ This is similar to this pointer in C++ and this reference in Java. 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. The __init__ method The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. # A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, My name is', self.name)
  • 7. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 p = Person('Muhammad Haroon') p.say_hi() Class and Instance Variables/attributes In the Python language, instance variables are variables whose value is assigned inside a constructor or method with self. Class variables are variables whose value is assigned in class. # Python program to show that the variables with a value # assigned in class declaration, are class variables and # variables inside methods and constructors are instance # variables. # Class for Computer Science Student class CSStudent: # Class Variable stream = 'cs' # The init method or constructor def __init__(self, roll): # Instance Variable self.roll = roll # Objects of CSStudent class a = CSStudent(1) b = CSStudent(2) print(a.stream) # prints "cs"
  • 8. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 print(b.stream) # prints "cs" print(a.roll) # prints 1 # Class variables can be accessed using class # name also print(CSStudent.stream) # prints "cs" We can define instance variables inside normal methods also. # Python program to show that we can create # instance variables inside methods # Class for Computer Science Student class CSStudent: # Class Variable stream = 'cs' # The init method or constructor def __init__(self, roll): # Instance Variable self.roll = roll # Adds an instance variable def setAddress(self, address): self.address = address # Retrieves instance variable def getAddress(self):
  • 9. OOP with Python mr.harunahmad2014@gmail.com CS/IT/SE/CSE Muhammad Haroon – PhD CS (Enrolled) from Hitec University Taxila 0300-7327761 return self.address # Code a = CSStudent(101) a.setAddress("Muhammad Haroon, Multan") print(a.getAddress()) How to create an empty class? We can create an empty class using pass statement in Python. # An empty class class Test: pass End