0% found this document useful (0 votes)
3 views39 pages

Python Programming Lecture5

The document provides an overview of Object Oriented Programming (OOP) concepts in Python, including class definitions, methods, operator overloading, properties, inheritance, and composition. It illustrates these concepts with code examples, demonstrating how to create classes, instantiate objects, and utilize various OOP features. Additionally, it covers introspection tools and built-in class attributes, enhancing the understanding of Python's OOP capabilities.

Uploaded by

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

Python Programming Lecture5

The document provides an overview of Object Oriented Programming (OOP) concepts in Python, including class definitions, methods, operator overloading, properties, inheritance, and composition. It illustrates these concepts with code examples, demonstrating how to create classes, instantiate objects, and utilize various OOP features. Additionally, it covers introspection tools and built-in class attributes, enhancing the understanding of Python's OOP capabilities.

Uploaded by

ph25c013
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented

Programming

112
Object Oriented Programming
# [Link]
class BankAccount:
def __init__(self, amount=0): # c’tor
self.__balance = amount
def withdraw(self, amount): # methods
self.__balance -= amount
return self.__balance
def deposit(self, amount):
self.__balance += amount
return self.__balance 113
Object Oriented Programming
>>> from account import BankAccount
>>> a = BankAccount(1000) # instances
>>> b = BankAccount()
>>> [Link](100) # -> deposit(a, 100)
100
>>> [Link](50)
50
>>> [Link](10)
40
>>> [Link](10)
90
114
The self parameter
● The first argument of every class instance method,
including __init__ and __del__, is an explicit reference
to the current instance of the class
● by convention, this argument is always named self, but it is
not a keyword
def __init__(self, amnt=0)
● In the __init__ method, self refers to the object being
created
● In other methods, self refers to the object
○ whenever an object calls its method, the object itself is
passed as the first argument
● The constructor is defined with two arguments, while an
object is created passing none!
a = BankAccount() # 2nd parameter has default value 115
Operator Overloading
class Integer:
def __init__(self, v=0):
self._value = v
def set(self, v):
self._value = v
def __add__(self, value):
return self._value + value
def __sub__(self, value):
return self._value - value
def __mul__(self, value):
return self._value * value
def __truediv__(self, value):
return self._value / value
def __gt__(self, value):
if self._value > value:
return 1
else:
return 0
def __lt__(self, value):
if self._value < value:
return 1
else:
return 0
def __eq__(self, value):
if self._value == value:
return 1
else: 116
return 0
Operator Overloading
class Integer:
def __init__(self, v=0):
if __name__ == '__main__':
self._value = v d = Integer(10)
def set(self, v): print(type(d))
self._value = v
def __add__(self, value):
return self._value + value print(d + 2)
def __sub__(self, value):
return self._value - value
print(d - 2)
def __mul__(self, value): print(d * 2)
return self._value * value print(d / 5)
def __truediv__(self, value):
return self._value / value
def __gt__(self, value): if d < 5:
if self._value > value:
return 1 print("Less than 5")
else: else:
return 0
def __lt__(self, value):
print("Not less than 5")
if self._value < value:
return 1 d = 10 # [Link](10)
else:
return 0 if d == 5:
def __eq__(self, value): print("Yes!")
if self._value == value:
return 1
else:
else: print("no...") 117
return 0
Operator Overloading

118
Property
class Track:
def __init__(self, artist, title, duration):
self._artist = artist
self._title = title
self._duration = duration

@property
def artist(self): # artist instead of artist()
return self._artist

@property
def title(self):
return self._title

@property
def duration(self):
return self._duration
def __str__(self):
return '%s - %s - %s' %(self._artist, self._title, self._duration)
119
Property
if __name__ == "__main__":
track = Track("Ravi Shankar", "Bairagi Todi", 25)
print(track)

# access directly
print ('%s - %s - %s' %
([Link], [Link], [Link]))

120
Class, Subclass
class Person: # base class
def __init__(self, name, age): # constructor
self._name = name
self._age = age
def introduce(self): # method
return 'Person - name: %s, age: %s'% \
(self._name, self._age)
def __str__(self):
return 'Person - name: %s, age: %s'% \
(self._name, self._age)

121
Class, Subclass
class Person: # base class
def __init__(self, name, age): # constructor
self._name = name
self._age = age
def introduce(self): # method
return 'Person - name: %s, age: %s'% \
(self._name, self._age)

class Student(Person): # derived class


""" A student class
"""
def __init__(self, name, age, id):
Person.__init__(self, name, age)
self._id = id
def introduce(self): # over-ridden method
return 'Student - name: %s,age: %s,id: %d'% \
(self._name, self._age, self._id)
122
Class, Subclass
if __name__ == "__main__":
p1 = Person('Tendulkar', 50)
p2 = Person('Dravid', 50)
[Link] = 'The Wall'

print([Link](), \
'nickname: ', [Link])

s1 = Student('Rahane', 32)
print([Link]())

123
Composition & Inheritance
# composition
class Stack:
def __init__(self):
self._stack = []
def push(self,object):
self._stack.append(object)
def pop(self):
return self._stack.pop()
def length(self):
return len(self._stack)
def __repr__(self):
return repr(self._stack)

124
Composition & Inheritance
# composition # inheritance
class Stack: class StackD(list):
def __init__(self): def push(self, obj):
self._stack = [] [Link](obj)
def push(self,object):
self._stack.append(object)
def pop(self):
return self._stack.pop()
def length(self):
return len(self._stack)
def __repr__(self):
return repr(self._stack)

125
Composition & Inheritance
if __name__ == "__main__":
# composition
s = Stack()
[Link]("Multiverse")
[Link](42)
[Link]([3,4,5])
print(s)
x = [Link]()
y = [Link]()
print(s)

126
Composition & Inheritance
if __name__ == "__main__":
# composition
s = Stack()
[Link]("Multiverse")
[Link](42)
[Link]([3,4,5])
print(s)
x = [Link]()
y = [Link]()
print(s)

# inheritance
# We can use StackD the same way
s = StackD() # etc. 127
__str__, __repr__, __call__

128
__repr__
class Rectangle:
def __init__(self, w=10, h=10):
self._width = w
self._height = h
def __repr__(self):
return 'Rectangle (width=%d,height=%d)' \
% (self._width, self._height)

129
__repr__
class Rectangle:
def __init__(self, w=10, h=10):
self._width = w
self._height = h
def __repr__(self):
return 'Rectangle (width=%d,height=%d)' \
% (self._width, self._height)

if __name__ == "__main__":
r = Rectangle()
print(r)
print(str(r))

r1 = Rectangle(2,2)
130
print(r1)
__str__
class Rectangle:
def __init__(self, w, h):
self._width = w
self._height = h
def area(self):
return self._width * self._height

131
__str__
class Rectangle:
def __init__(self, w, h):
self._width = w
self._height = h
def area(self):
return self._width * self._height

if __name__ == '__main__':
r1 = Rectangle(100,20)
print(r1)
<__main__.Rectangle object at 0x7f93a8706fd0>

132
__str__
class Rectangle:
def __init__(self, w, h):
self._width = w
self._height = h
def area(self):
return self._width * self._height
def __str__(self):
return '(Rectangle: %s, %s)' % \
(self._width, self._height)

133
__str__
class Rectangle:
def __init__(self, w, h):
self._width = w
self._height = h
def area(self):
return self._width * self._height
def __str__(self):
return '(Rectangle: %s, %s)' % \
(self._width, self._height)

if __name__ == '__main__':
r1 = Rectangle(100,20)
print(r1)
(Rectangle: 100, 20)
134
__call__
class Foo:
def __call__(self):
print('called')

foo_instance = Foo()

# calls the __call__ method


foo_instance()

135
class & static methods
from datetime import date

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
@classmethod
def fromBirthYear(classname, name, year):
return classname(name,[Link]().year -year)
@staticmethod
def isAdult(age):
return age > 18

136
class & static methods
>>> p0 = Person()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 3
arguments (1 given)

>>> p1 = Person('Ajinka', 27)


>>> p2 = [Link]('Ajinka',
1996)
>>> print [Link]
>>> print [Link] # print the result
>>> print [Link](22)
137
Built-in class attributes
>>> class Account():
... ''' A class defines a new data type '''
... pass
...
>>> dir(Account)
['__class__', '__delattr__', '__dict__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '__weakref__']
>>> type(Account)
<class 'type'>
>>> type(Account())
<class '__main__.Account'>
138
Built-in class attributes
>>> Account.__name__
'Account'
>>> Account.__doc__
'A class defines a new data type'
>>> Account.__module__
'__main__'
>>> Account.__bases__
(<class 'object'>,)

139
Derived class attributes
>>> dir(Student)
['__doc__', '__init__', '__module__']
>>> Student.__bases__
(__main__.Person,)
>>> Student.__doc__
' A student class\n '

140
Introspection

141
Introspection in Computing
● Ability to determine object type, find attributes
and capabilities at runtime
● Support for introspection is an integral part of
Python
○ runs deep and wide throughout the language
● Other languages
○ C++ has minimal support (RTTI)
■ External libraries provide necessary support (reflex)
○ Java has extensive support (Reflection)
○ Perl: adequate support, not used extensively
○ Ruby, Julia: same level as Python
142
Introspection – Python Tools
● dir()
● type(), id(), str(), repr()
● callable()
● hasattr(), getattr(), setattr(),
delattr()
● isinstance(), issubclass()
● modules: types, inspect
● Reference:
○ [Link]/lang/python/introspection
○ [Link]/developerworks/linux/library/l-pyint/in
[Link]
○ [Link]/power_of_introspection/ 143
Object attributes
● access and manipulate object attributes
with
− getattr(obj, name[, default])
− hasattr(obj, name)
− setattr(obj, name, value)
− delattr(obj, name)

144
type()
>>> type(dir)
>>> type(dir())

>>> import sys


>>> import math

>>> type(len) # function


>>> type(sys) # module
>>> type(type) # type

>>> type(1)
<class 'int'>
>>> type(1) is int
True
>>> type(int) is type
True 145
str(), repr()
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__file__',
'__name__', '__package__', 'date', 'datetime',
'datetime_CAPI', 'time', 'timedelta', 'tzinfo']

>>> type([Link])
<class 'type'>
>>> today = [Link]()
>>> type(today)
<class '[Link]'>

>>> today
[Link](2014, 4, 14, 19, 58, 35, 828815)
>>> str(today)
'2014-04-14 19:58:35.828815'
>>> repr(today)
146
'[Link](2014, 4, 14, 19, 58, 35, 828815)'
Class, Subclass
class Person(object):
def __init__(self, name, age): # constructor
[Link] = name
[Link] = age
def intro(self): # method
return 'name:%s and age:%s'%([Link],[Link])

class Student(Person):
pass

p1 = Person('Sachin', 40)
p2 = Person('Rahul', 40)
[Link] = 'The Wall'

s1 = Student('Ajinka', 21)
147
isinstance(), issubclass()
print type(Person)
print type(p1)

print type(Student)
print type(s1)

print isinstance(p1, Person)


print isinstance(s1, Person)
print isinstance(p1, Student)
print isinstance(s1, Student)

print issubclass(Person, Student)


print issubclass(Student, Person)

148
hasattr(), getattr()
>>> li = ['Larry', 'Guido', 'Yukihiro']
>>> [Link]
<built-in method pop of list object at 0x7fe80e6293b0>
>>> getattr(li, 'pop')
<built-in method pop of list object at 0x7fe80e6293b0>

>>> f = getattr(li, 'pop')


>>> f()
'Yukihiro'
>>> getattr(li, 'pop')()
'Guido'

>>> getattr(li, 'append')('Brent')


>>> li
['Larry', 'Brent']
>>> hasattr(li, 'clear')
False
>>> hasattr(li, 'insert')
True 149
callable()
>>> import string
>>> type(string)
<class 'module'>

>>> dir(string)
[..., 'find', 'hexdigits', 'index', 'index_error', 'join',
'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip',
'maketrans', 'octdigits', 'printable', 'punctuation', 'replace',
'rfind', ... 'upper', 'uppercase', 'whitespace', 'zfill']

>>> [Link]
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

>>> [Link]
<function join at 0x7f19f2bc42a8>

>>> callable([Link])
True

>>> callable([Link])
False
150
>>>

You might also like