Understanding Python OOP Concepts
Understanding Python OOP Concepts
Objects
CS1302 Introduction to Computer Programming
%reload_ext divewidgets
Definitions
{important}
[Link] 1/27
2025/2/20 20:04 Objects
In [3]: %%html
<iframe width="800" height="450" src="[Link]
An error occurred.
Try watching this video on [Link], or enable JavaScript if it is disabled in your browser.
Exercise Define
{hint}
See the [documentation]([Link] and
[tutorial]
([Link]
started-animating-with-manim-and-python-3-7/).
[Link] 2/27
2025/2/20 20:04 Objects
{important}
What is an object?
In one paragraph, explain what is the difference between class and object in pyt
Out[5]: In Python, a class and an object are two distinct concepts. A class is a bluepr
int or a template that defines the properties and behavior of an object, wherea
s an object is an instance of a class, representing a specific entity with its
own set of attributes (data) and methods (functions). In other words, a class i
s a design pattern or a template, while an object is a real-world entity that i
s created based on that template. For example, "Car" can be a class with attrib
utes like color, model, and methods like start_engine, accelerate, whereas "my_
car" can be an object of the "Car" class, with its own specific attributes like
red color, Toyota model, and its own methods like starting its engine, accelera
ting to 60mph. This distinction is crucial in object-oriented programming, as i
t allows for the creation of multiple objects from a single class, each with it
s own unique characteristics.
Class vs Object
[Link] 3/27
2025/2/20 20:04 Objects
Class vs Object.
For example, a car has wheels and color, so wheel and color are the
attribute/member of car
In program, an object has some variables and functions, they are called
member variable and member function
To use the attribute/member of an object, we use member operator .
The syntax to use a variable/function of an object is object.variable_name
or object.function_name() , e.g., [Link], [Link]()
Please provide a sample python code to construct a car class and create diffrent
[Link] 4/27
2025/2/20 20:04 Objects
Out[13]:
Car Class in Python
The following Python code constructs a Car class with attributes like color, model,
year, and mileage. It also includes methods to start the engine, accelerate, and
display car details.
class Car:
def __init__(self, color, model, year, mileage):
[Link] = color
[Link] = model
[Link] = year
[Link] = mileage
self.engine_status = "Stopped"
self.current_speed = 0
def start_engine(self):
self.engine_status = "Started"
def display_details(self):
return f"Color: {[Link]}\nModel: {[Link]}\nYear: {[Link]}\nMileage: {s
[Link]} miles\nEngine Status: {self.engine_status}\nCurrent Speed: {[Link]
t_speed} mph"
[Link] 5/27
2025/2/20 20:04 Objects
Example Output
Car 1 Details
Color: Red Model: Toyota Year: 2020 Mileage: 100 miles Engine Status: Started
Current Speed: 60 mph
Car 2 Details
Color: Blue Model: Honda Year: 2015 Mileage: 30500 miles Engine Status: Started
Current Speed: 70 mph
Car 3 Details
Color: Black Model: Ford Year: 2018 Mileage: 200 miles Engine Status: Started
Current Speed: 80 mph
Parameters :
Returns : True, if object belongs to the given class/type, else returns False.
Out[14]: True
In [15]: (
isinstance(1, object)
and isinstance(1.0, object)
and isinstance("1", object)
and isinstance(True, object)
and isinstance(None, object)
and isinstance(__builtin__, object)
[Link] 6/27
2025/2/20 20:04 Objects
Out[15]: True
Out[16]: True
{note}
f = f(f)
There exist several f in the following python code. Please explain them one by o
def f(f):
return f
f = f(f)
[Link] 7/27
2025/2/20 20:04 Objects
When the function `f` is called with itself as the argument, it creates a scope
where the local variable `f` (the function argument) shadows the global functio
n `f`. However, because the function `f` simply returns its argument, it return
s the local `f`, which is the function object itself.
identity_func = identity
identity = identity_func(identity_func)
```
In this example, we define an `identity` function that returns its argument. We
then assign the function object to a new name `identity_func`. Finally, we reas
sign the name `identity` to the result of calling `identity_func` with itself a
s the argument, similar to the original code.
Exercise
[Link] 8/27
2025/2/20 20:04 Objects
In [19]: #solution
print(isinstance(type, object))
print(isinstance(object, type))
True
True
{important}
An object can be an instance of more than one types.
Out[20]: True
Out[21]: True
Exercise
Check whether type is a subclass of object and vice versa. (Is the result
reasonable?)
In [23]: #Solution
print(issubclass(type, object))
print(issubclass(object, type))
[Link] 9/27
2025/2/20 20:04 Objects
True
False
Out[24]: In Python, `object` is not a subclass of `type` because `object` is the base cl
ass of all objects, while `type` is a metaclass that creates classes. The relat
ionship between `object` and `type` is more nuanced: `type` is the metaclass th
at created the `object` class, and `object` is an instance of `type`. This mean
s that `type` is the class of `object`, not its superclass. To illustrate this,
`isinstance(object, type)` returns `True`, indicating that `object` is an insta
nce of `type`, but `issubclass(object, type)` returns `False`, indicating that
`object` is not a subclass of `type`. This distinction is fundamental to Pytho
n's object model and metaclass hierarchy.
What is an attribute?
{important}
check if an object has the given named attribute and return true if present,
else false.
Complex number
(1+2j)
1.0
2.0
complex conjugate is when "Each of two complex numbers having their real
parts identical and their imaginary parts of equal magnitude but opposite
sign."
[Link] 10/27
2025/2/20 20:04 Objects
In [26]: X=complex(1,2)
print(X)
#method 1
print([Link](X))
#method 2
print([Link]())
(1+2j)
(1-2j)
(1-2j)
In [28]: dir(complex("1+j"))
[Link] 11/27
2025/2/20 20:04 Objects
Out[28]: ['__abs__',
'__add__',
'__bool__',
'__class__',
'__complex__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__mul__',
'__ne__',
'__neg__',
'__new__',
'__pos__',
'__pow__',
'__radd__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmul__',
'__rpow__',
'__rsub__',
'__rtruediv__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__truediv__',
'conjugate',
'imag',
'real']
Different objects of a class have the same set of attributes as that of the class.
Out[29]: True
Out[30]: True
[Link] 12/27
2025/2/20 20:04 Objects
Different objects of the same class can still behave differently because their
attribute values can be different.
Out[31]: False
[Link] 13/27
2025/2/20 20:04 Objects
Out[34]: ['__call__',
'__class__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__name__',
'__ne__',
'__new__',
'__qualname__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__self__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__text_signature__']
Object Aliasing
What is object Aliasing?
x=5
y=x
x and y refer to the same object (i.e., 5). We say that, y is alias (another name)
of x.
Two objects are the same if they occupy the same memory.
The keyword is checks whether two objects are the same object.
[Link] 14/27
2025/2/20 20:04 Objects
f(f) is f
Out[36]: True
Is is the same as == ?
is simply checks whether two objects occupy the same memory, but
== calls the method ( __eq__ ) of the operands to checks the equality in
value.
To see this, we can use the function id which returns an id number for an object
based on its memory location.
[Link] 15/27
2025/2/20 20:04 Objects
{caution}
File Objects
How to read a text file?
[Link] 16/27
2025/2/20 20:04 Objects
It's very often programmers may forget to close a file, how to solve this problem?
The with statement applies to any context manager that provides the methods
[Link] 17/27
2025/2/20 20:04 Objects
In [45]: f=open('[Link]')
print([Link]) #to check whether a file is closed or not
[Link]()
print([Link]) #after we run [Link]() to close the file, [Link] returns True
False
True
As a file may contain many lines? how to read a file line by line?
In [47]: with open('[Link]') as f: #use with statement to create a file object and
line_no = 1 #create a variable to represent line no
for line in f: #use a for loop to read each line
if line_no <= 5: #if line no is <5, we print it
print(line, end='')
line_no += 1
f = open('[Link]', 'r')
f2 = open('[Link]', 'w')
[Link] 18/27
2025/2/20 20:04 Objects
f3 = open('[Link]', 'a')
In [48]: #first, create a string to represent the file name and directory
destination = 'private/new_contact.csv'
private
[Link] 19/27
2025/2/20 20:04 Objects
The argument 'w' in open() sets the file object to write mode.
The method write writes the input strings to the file.
In this mode, the original data will be lost
!more {destination}
Note that the file object does not provide any method to delete the file.
Instead, we should use the function remove of the os module.
Syntax: [Link](file_directory)
A short summary
What you need to know for file objects.
[Link] 20/27
2025/2/20 20:04 Objects
String Objects
A string is an object, and actually it has many built-in functions
Syntax: [Link](substring)
Returns the lowest index where the string parameter is found as a substring
of the input string; returns -1 if not found
0
-1
In [55]: # str1='a,b,c,d'
# str2='a-b-c-d'
[Link] 21/27
2025/2/20 20:04 Objects
print('Example 2:')
print([Link](',',1))
print([Link]('-',1))
print([Link](',',1))
print([Link]('-',1))
Example 2:
['a', 'b,c,d']
['a', 'b-c-d']
['a,b,c', 'd']
['a-b-c', 'd']
Example 3:
['a', 'b,c,d']
['a', 'b-c-d']
['a,b,c', 'd']
['a-b-c', 'd']
The list of substrings can be joined back together using the join methods.
Syntax: [Link](substrings)
Join all items into a single string, separated by delimiter
In [56]: substrings=['ba','na','na']
print('-'.join(substrings))
print('*'.join(substrings))
print(''.join(substrings))
ba-na-na
ba*na*na
banana
Syntax: [Link](character)
remove any leading/trailing characters, by default it's whitespace
If the chars argument is not provided, all leading and trailing whitespaces are
removed from the string.
[Link](character) , l means left: remove characters on the left side
of a string
[Link](character) , r means right: remove characters on the right
side of a string
[Link] 22/27
2025/2/20 20:04 Objects
banana
banana
banana
banana
,,,banana,,,
banana
banana,,,
,,,banana
The upper() method returns a string where all characters are in upper case.
The lower() method returns a string where all characters are in lower case.
In [58]: string="apple"
print([Link]())
string2="APPle"
print([Link]())
APPLE
apple
In [59]: print(1+10)
print('1'+'10')
11
110
print(MyStr(1) + 2, 2 + MyStr(1))
What is overloading?
Recall that the addition operation + behaves differently for different types.
[Link] 23/27
2025/2/20 20:04 Objects
Dispatch on type
The strategy of checking the type for the appropriate implementation is called
dispatching on type.
It can get quite messy with all possible types and combinations.
In [63]: for x, y in ((1, 1.1), (1, complex(1, 2)), ((1, 2), (1, 2))):
print(f"{x!r:^10} + {y!r:^10} = {x+y!r}")
1 + 1.1 = 2.1
1 + (1+2j) = (2+2j)
(1, 2) + (1, 2) = (1, 2, 1, 2)
[Link] 24/27
2025/2/20 20:04 Objects
1/2 + 1 = 3/2
1 + 1/2 = 3/2
{caution}
Data-directed programming
The idea is to treat an implementation as a datum that can be returned by the
operand types.
{important}
- `x + y` is a [*syntactic sugar*]
([Link] that
- invokes the method `type(x).__add__(x,y)` of `type(x)` to do
the addition.
1/2 + 1 = 3/2
1 + 1/2 = NotImplemented
The first case calls Fraction.__add__ , which provides a way to add int to
Fraction .
The second case calls int.__add__ , which cannot provide any way of adding
Fraction to int . (Why not?)
[Link] 25/27
2025/2/20 20:04 Objects
{important}
{note}
Exercise
Explain how the addition operation for the class MyStr behaves differently as
compared to str .
MyStr(1) + 2, 2 + MyStr(1)
[Link] 26/27
2025/2/20 20:04 Objects
Solution:
Unlike str which cannot be added to instances of other types such as int ,
MyStr can be added (concatenated) or reverse added to instances of other types.
This is achieved by overloading the + operation with the new implementations
of the forward/reverse addition methods __add__ and __radd__ .
Summary
1. Understand some concepts such as class, object and object-oriented
programming.
In [ ]:
[Link] 27/27