SlideShare a Scribd company logo
2
What are Objects?
• An object is a location in memory having a value and
possibly referenced by an identifier.
• In Python, every piece of data you see or come into contact
with is represented by an object.
>>>𝑠𝑡𝑟 = "This is a String"
>>>dir(str)
…..
>>>str.lower()
‘this is a string’
>>>str.upper()
‘THIS IS A STRING’
• Each of these objects has three
components:
I. Identity
II. Type
III. Value
Arslan Arshad (2K12-BSCS-37)
Most read
3
Defining a Class
Arslan Arshad (2K12-BSCS-37)
Most read
7
Defining a 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.
• Other class methods declared as normal functions with the
exception that the first argument to each method is self.
• Self: This is a Python convention. There's nothing magic
about the word self.
• The first argument in __init__() and other function gets is
used to refer to the instance object, and by convention, that
argument is called self.
Arslan Arshad (2K12-BSCS-37)
Most read
Object Oriented
Programming with Python
Arslan Arshad (2K12-BSCS-37)
What are Objects?
• An object is a location in memory having a value and
possibly referenced by an identifier.
• In Python, every piece of data you see or come into contact
with is represented by an object.
>>>𝑠𝑡𝑟 = "This is a String"
>>>dir(str)
…..
>>>str.lower()
‘this is a string’
>>>str.upper()
‘THIS IS A STRING’
• Each of these objects has three
components:
I. Identity
II. Type
III. Value
Arslan Arshad (2K12-BSCS-37)
Defining a Class
Arslan Arshad (2K12-BSCS-37)
Defining a Class
• Python’s class mechanism adds classes with a minimum of new
syntax and semantics.
• It is a mixture of the class mechanisms found in C++ and Modula-
3.
• As C++, Python class members are public and have Virtual
Methods.
The simplest form of class
definition looks like this:
𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑁𝑎𝑚𝑒:
<statement 1>
<statement 2>
.
.
.
<statement N>
• A basic class consists only of the
𝑐𝑙𝑎𝑠𝑠 keyword.
• Give a suitable name to class.
• Now You can create class members
such as data members and member
function.
Arslan Arshad (2K12-BSCS-37)
Defining a Class
• As we know how to create a Function.
• Create a function in class MyClass named func().
• Save this file with extension .py
• You can create object by invoking class name.
• Python doesn’t have new keyword
• Python don’t have new keyword because everything in python is
an object.
𝑐𝑙𝑎𝑠𝑠 𝑀𝑦𝐶𝑙𝑎𝑠𝑠:
“””A simple Example
of class”””
i=12
def func(self):
return ‘’Hello World
>>>𝑜𝑏𝑗 = 𝑀𝑦𝐶𝑙𝑎𝑠𝑠
>>> obj.func()
‘Hello World’
>>>𝑜𝑏𝑗 = 𝑀𝑦𝐶𝑙𝑎𝑠𝑠
>>> obj.func()
‘Hello World’
Arslan Arshad (2K12-BSCS-37)
Defining a Class
1. class Employee:
2. 'Common base class for all employees‘
3. empCount = 0
4. def __init__(self, name, salary):
5. self.name = name
6. self.salary = salary
7. Employee.empCount += 1
8. def displayCount(self):
9. print("Total Employee %d" % Employee.empCount)
10. def displayEmployee(self):
11. print("Name : ", self.name, ", Salary: ", self.salary)
Arslan Arshad (2K12-BSCS-37)
Defining a 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.
• Other class methods declared as normal functions with the
exception that the first argument to each method is self.
• Self: This is a Python convention. There's nothing magic
about the word self.
• The first argument in __init__() and other function gets is
used to refer to the instance object, and by convention, that
argument is called self.
Arslan Arshad (2K12-BSCS-37)
Creating instance objects
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000 )
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
• To create instances of a class, you call the class using class name and
pass in whatever arguments its __init__ method accepts.
• During creating instance of class. Python adds the self argument to
the list for you. You don't need to include it when you call the
methods
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
2
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
Output
Arslan Arshad (2K12-BSCS-37)
Special Class Attributes in Python
• Except for self-defined class attributes in Python,
class has some special attributes. They are provided
by object module.
Arslan Arshad (2K12-BSCS-37)
Attributes Name Description
__dict__ Dict variable of class name space
__doc__ Document reference string of class
__name__ Class Name
__module__ Module Name consisting of class
__bases__ The tuple including all the superclasses
Form and Object for Class
• Class includes two members: form and object.
• The example in the following can reflect what is the
difference between object and form for class.
Arslan Arshad (2K12-BSCS-37)
Invoke form: just invoke data or
method in the class, so i=123
Invoke object: instantialize object
Firstly, and then invoke data or
Methods.
Here it experienced __init__(),
i=12345
Class Scope
• Another important aspect of Python classes is scope.
• The scope of a variable is the context in which it's
visible to the program.
• Variables that are available everywhere (Global
Variables)
• Variables that are only available to members of a
certain class (Member variables).
• Variables that are only available to particular
instances of a class (Instance variables).
Arslan Arshad (2K12-BSCS-37)
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.
• You normally won't notice when the garbage collector
destroys an orphaned instance and reclaims its space
• But a class can implement the special method __del__(),
called a destructor
• This method might be used to clean up any non-memory
resources used by an instance.
Arslan Arshad (2K12-BSCS-37)
Destroying Objects (Garbage
Collection):
Arslan Arshad (2K12-BSCS-37)
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>
Class Inheritance:
• Instead of starting from scratch, you can create a class by deriving it
from a preexisting class by listing the parent class in parentheses after
the new class name.
• Like Java subclass can invoke Attributes and methods in superclass.
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Syntax
• Python support multiple inheritance but we will only
concern single parent inheritance.
Arslan Arshad (2K12-BSCS-37)
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'
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
Static Variable
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
Output
Arslan Arshad (2K12-BSCS-37)
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.
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
Arslan Arshad (2K12-BSCS-37)
Overloading Operators:
• In python we also overload operators as there we
overload ‘+’ operator.
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (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)
Arslan Arshad (2K12-BSCS-37)
Method Overloading
• In python method overloading is not acceptable.
• This will be against the spirit of python to worry a lot about
what types are passed into methods.
• Although you can set default value in python which will be a
better way.
• Or you can do something with tuples or lists like this…
Arslan Arshad (2K12-BSCS-37)
def print_names(names):
"""Takes a space-delimited string or an iterable"""
try:
for name in names.split(): # string case
print name
except AttributeError:
for name in names:
print name
Polymorphism:
• Polymorphism is an important definition in OOP. Absolutely,
we can realize polymorphism in Python just like in JAVA. I
call it “traditional polymorphism”
• In the next slide, there is an example of polymorphism in
Python.
• But in Python,
Arslan Arshad (2K12-BSCS-37)
Only traditional polymorphism exist?
Polymorphism:
Arslan Arshad (2K12-BSCS-37)
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement
abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'), Cat('Mr. Mistoffelees'), Dog('Lassie')]
for animal in animals:
Print(animal.name + ': ' + animal.talk())
Everywhere is polymorphism in
Python
• So, in Python, many operators have the property of
polymorphism. Like the following example:
Arslan Arshad (2K12-BSCS-37)
• Looks stupid, but the key is that variables can support any
objects which support ‘add’ operation. Not only integer
but also string, list, tuple and dictionary can realize their
relative ‘add’ operation.
References:
• http://www.tutorialspoint.com/python/python_classes_obj
ects.htm
• http://www.codecademy.com/courses/python-
intermediate-en-
WL8e4/1/4?curriculum_id=4f89dab3d788890003000096
• http://stackoverflow.com/
• https://www.python.org/
• http://en.wikipedia.org/wiki/Python_(programming_langua
ge)
• http://www.cs.colorado.edu/~kena/classes/5448/f12/prese
ntation-materials/li.pdf
Arslan Arshad (2K12-BSCS-37)

More Related Content

What's hot (20)

Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
Karudaiyar Ganapathy
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
Raghunath A
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
Pritom Chaki
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
Prognoz Technologies Pvt. Ltd.
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
harsh kothari
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
Home
 
Java packages
Java packagesJava packages
Java packages
BHUVIJAYAVELU
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
Raghunath A
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
Pritom Chaki
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
Home
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 

Viewers also liked (16)

Python Objects
Python ObjectsPython Objects
Python Objects
Quintagroup
 
Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)
iloveallahsomuch
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
P3 InfoTech Solutions Pvt. Ltd.
 
Python an-intro v2
Python an-intro v2Python an-intro v2
Python an-intro v2
Arulalan T
 
Python avancé : Classe et objet
Python avancé : Classe et objetPython avancé : Classe et objet
Python avancé : Classe et objet
ECAM Brussels Engineering School
 
CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)
Rubén Izquierdo Beviá
 
Oop’s Concept and its Real Life Applications
Oop’s Concept and its Real Life ApplicationsOop’s Concept and its Real Life Applications
Oop’s Concept and its Real Life Applications
Shar_1
 
Java Object-Oriented Programming Conecpts(Real-Time) Examples
Java Object-Oriented Programming Conecpts(Real-Time) ExamplesJava Object-Oriented Programming Conecpts(Real-Time) Examples
Java Object-Oriented Programming Conecpts(Real-Time) Examples
Shridhar Ramesh
 
Python avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementiellePython avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementielle
ECAM Brussels Engineering School
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
Ranel Padon
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
Nina Zakharenko
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
OXUS 20
 
Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)
iloveallahsomuch
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
P3 InfoTech Solutions Pvt. Ltd.
 
Python an-intro v2
Python an-intro v2Python an-intro v2
Python an-intro v2
Arulalan T
 
CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)
Rubén Izquierdo Beviá
 
Oop’s Concept and its Real Life Applications
Oop’s Concept and its Real Life ApplicationsOop’s Concept and its Real Life Applications
Oop’s Concept and its Real Life Applications
Shar_1
 
Java Object-Oriented Programming Conecpts(Real-Time) Examples
Java Object-Oriented Programming Conecpts(Real-Time) ExamplesJava Object-Oriented Programming Conecpts(Real-Time) Examples
Java Object-Oriented Programming Conecpts(Real-Time) Examples
Shridhar Ramesh
 
Python avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementiellePython avancé : Interface graphique et programmation évènementielle
Python avancé : Interface graphique et programmation évènementielle
ECAM Brussels Engineering School
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
Ranel Padon
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
Nina Zakharenko
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
OXUS 20
 
Ad

Similar to Object oriented programming with python (20)

Python3
Python3Python3
Python3
Ruchika Sinha
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Python advance
Python advancePython advance
Python advance
Mukul Kirti Verma
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Module-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptxModule-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptx
YogeshKumarKJMIT
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Problem solving with python programming OOP's Concept
Problem solving with python programming OOP's ConceptProblem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Module-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptxModule-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptx
YogeshKumarKJMIT
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Problem solving with python programming OOP's Concept
Problem solving with python programming OOP's ConceptProblem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Ad

Recently uploaded (20)

Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
GIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of UtilitiesGIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of Utilities
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
FME Beyond Data Processing Creating A Dartboard Accuracy App
FME Beyond Data Processing Creating A Dartboard Accuracy AppFME Beyond Data Processing Creating A Dartboard Accuracy App
FME Beyond Data Processing Creating A Dartboard Accuracy App
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
GIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of UtilitiesGIS and FME: The Foundation to Improve the Locate Process of Utilities
GIS and FME: The Foundation to Improve the Locate Process of Utilities
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
FME Beyond Data Processing Creating A Dartboard Accuracy App
FME Beyond Data Processing Creating A Dartboard Accuracy AppFME Beyond Data Processing Creating A Dartboard Accuracy App
FME Beyond Data Processing Creating A Dartboard Accuracy App
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 

Object oriented programming with python

  • 1. Object Oriented Programming with Python Arslan Arshad (2K12-BSCS-37)
  • 2. What are Objects? • An object is a location in memory having a value and possibly referenced by an identifier. • In Python, every piece of data you see or come into contact with is represented by an object. >>>𝑠𝑡𝑟 = "This is a String" >>>dir(str) ….. >>>str.lower() ‘this is a string’ >>>str.upper() ‘THIS IS A STRING’ • Each of these objects has three components: I. Identity II. Type III. Value Arslan Arshad (2K12-BSCS-37)
  • 3. Defining a Class Arslan Arshad (2K12-BSCS-37)
  • 4. Defining a Class • Python’s class mechanism adds classes with a minimum of new syntax and semantics. • It is a mixture of the class mechanisms found in C++ and Modula- 3. • As C++, Python class members are public and have Virtual Methods. The simplest form of class definition looks like this: 𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑁𝑎𝑚𝑒: <statement 1> <statement 2> . . . <statement N> • A basic class consists only of the 𝑐𝑙𝑎𝑠𝑠 keyword. • Give a suitable name to class. • Now You can create class members such as data members and member function. Arslan Arshad (2K12-BSCS-37)
  • 5. Defining a Class • As we know how to create a Function. • Create a function in class MyClass named func(). • Save this file with extension .py • You can create object by invoking class name. • Python doesn’t have new keyword • Python don’t have new keyword because everything in python is an object. 𝑐𝑙𝑎𝑠𝑠 𝑀𝑦𝐶𝑙𝑎𝑠𝑠: “””A simple Example of class””” i=12 def func(self): return ‘’Hello World >>>𝑜𝑏𝑗 = 𝑀𝑦𝐶𝑙𝑎𝑠𝑠 >>> obj.func() ‘Hello World’ >>>𝑜𝑏𝑗 = 𝑀𝑦𝐶𝑙𝑎𝑠𝑠 >>> obj.func() ‘Hello World’ Arslan Arshad (2K12-BSCS-37)
  • 6. Defining a Class 1. class Employee: 2. 'Common base class for all employees‘ 3. empCount = 0 4. def __init__(self, name, salary): 5. self.name = name 6. self.salary = salary 7. Employee.empCount += 1 8. def displayCount(self): 9. print("Total Employee %d" % Employee.empCount) 10. def displayEmployee(self): 11. print("Name : ", self.name, ", Salary: ", self.salary) Arslan Arshad (2K12-BSCS-37)
  • 7. Defining a 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. • Other class methods declared as normal functions with the exception that the first argument to each method is self. • Self: This is a Python convention. There's nothing magic about the word self. • The first argument in __init__() and other function gets is used to refer to the instance object, and by convention, that argument is called self. Arslan Arshad (2K12-BSCS-37)
  • 8. Creating instance objects "This would create first object of Employee class" emp1 = Employee("Zara", 2000 ) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) • To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts. • During creating instance of class. Python adds the self argument to the list for you. You don't need to include it when you call the methods emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount 2 Name : Zara ,Salary: 2000 Name : Manni ,Salary: 5000 Total Employee 2 Output Arslan Arshad (2K12-BSCS-37)
  • 9. Special Class Attributes in Python • Except for self-defined class attributes in Python, class has some special attributes. They are provided by object module. Arslan Arshad (2K12-BSCS-37) Attributes Name Description __dict__ Dict variable of class name space __doc__ Document reference string of class __name__ Class Name __module__ Module Name consisting of class __bases__ The tuple including all the superclasses
  • 10. Form and Object for Class • Class includes two members: form and object. • The example in the following can reflect what is the difference between object and form for class. Arslan Arshad (2K12-BSCS-37) Invoke form: just invoke data or method in the class, so i=123 Invoke object: instantialize object Firstly, and then invoke data or Methods. Here it experienced __init__(), i=12345
  • 11. Class Scope • Another important aspect of Python classes is scope. • The scope of a variable is the context in which it's visible to the program. • Variables that are available everywhere (Global Variables) • Variables that are only available to members of a certain class (Member variables). • Variables that are only available to particular instances of a class (Instance variables). Arslan Arshad (2K12-BSCS-37)
  • 12. 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. • You normally won't notice when the garbage collector destroys an orphaned instance and reclaims its space • But a class can implement the special method __del__(), called a destructor • This method might be used to clean up any non-memory resources used by an instance. Arslan Arshad (2K12-BSCS-37)
  • 13. Destroying Objects (Garbage Collection): Arslan Arshad (2K12-BSCS-37) 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>
  • 14. Class Inheritance: • Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name. • Like Java subclass can invoke Attributes and methods in superclass. class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite Syntax • Python support multiple inheritance but we will only concern single parent inheritance. Arslan Arshad (2K12-BSCS-37)
  • 15. 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' 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 Static Variable Calling child constructor Calling child method Calling parent method Parent attribute : 200 Output Arslan Arshad (2K12-BSCS-37)
  • 16. 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. 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 Arslan Arshad (2K12-BSCS-37)
  • 17. Overloading Operators: • In python we also overload operators as there we overload ‘+’ operator. class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (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) Arslan Arshad (2K12-BSCS-37)
  • 18. Method Overloading • In python method overloading is not acceptable. • This will be against the spirit of python to worry a lot about what types are passed into methods. • Although you can set default value in python which will be a better way. • Or you can do something with tuples or lists like this… Arslan Arshad (2K12-BSCS-37) def print_names(names): """Takes a space-delimited string or an iterable""" try: for name in names.split(): # string case print name except AttributeError: for name in names: print name
  • 19. Polymorphism: • Polymorphism is an important definition in OOP. Absolutely, we can realize polymorphism in Python just like in JAVA. I call it “traditional polymorphism” • In the next slide, there is an example of polymorphism in Python. • But in Python, Arslan Arshad (2K12-BSCS-37) Only traditional polymorphism exist?
  • 20. Polymorphism: Arslan Arshad (2K12-BSCS-37) class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr. Mistoffelees'), Dog('Lassie')] for animal in animals: Print(animal.name + ': ' + animal.talk())
  • 21. Everywhere is polymorphism in Python • So, in Python, many operators have the property of polymorphism. Like the following example: Arslan Arshad (2K12-BSCS-37) • Looks stupid, but the key is that variables can support any objects which support ‘add’ operation. Not only integer but also string, list, tuple and dictionary can realize their relative ‘add’ operation.
  • 22. References: • http://www.tutorialspoint.com/python/python_classes_obj ects.htm • http://www.codecademy.com/courses/python- intermediate-en- WL8e4/1/4?curriculum_id=4f89dab3d788890003000096 • http://stackoverflow.com/ • https://www.python.org/ • http://en.wikipedia.org/wiki/Python_(programming_langua ge) • http://www.cs.colorado.edu/~kena/classes/5448/f12/prese ntation-materials/li.pdf Arslan Arshad (2K12-BSCS-37)

Editor's Notes

  • #6: C++ is a complicated beast, and the new keyword was used to distinguish between something that needed delete later and something that would be automatically reclaimed. In Java and C#, they dropped the delete keyword because the garbage collector would take care of it for you. The problem then is why did they keep the new keyword? Without talking to the people who wrote the language it's kind of difficult to answer. My best guesses are listed below: It was semantically correct. If you were familiar with C++, you knew that the new keyword creates an object on the heap. So, why change expected behavior? It calls attention to the fact that you are instantiating an object rather than calling a method. With Microsoft code style recommendations, method names start with capital letters so there can be confusion. Ruby is somewhere in between Python and Java/C# in it's use of new. Basically you instantiate an object like this: f = Foo.new()It's not a keyword, it's a static method for the class. What that means is that if you want a singleton, you can override the default implementation of new() to return the same instance every time. It's not necessarily recommended, but it's possible.
  • #12: 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.