module4_python
module4_python
Learning Objectives:
1. Understand the use of init () method and the self parameter. Correctly declare a class object.
2. Recognize the difference between functions and methods and the scope of methods, and make method
calls.
3. Understand how the level of inheritance affect method calls and variables.
So, we will build the LibraryBook class to store data about each book and support methods/operations
needed in the Library System.
Classes are blueprints or designs or templates for instances. The relationship between a class and an
instance is similar to the one between a cookie cutter and a cookie.
A single cookie cutter can make any number of cookies. The cutter defines the shape of the cookie.
The cookies are edible, but the cookie cutter is not.
In [ ]: type(my_book)
Out[ ]: __main__.LibraryBook
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 1/9
27/12/2024, 16:39 module4_python
Out[ ]: True
Objects simplify problems by providing an abstraction over certain data types and their functionality.
Instead of thinking of the problem in terms of individual strings, integers, etc. we can now
think in terms of LibraryBooks (or other objects).
Encapsulation
Data fields - Each instance owns its own data (the class can define what names the data fields have).
The init(self, ...) method is automatically called by Python when a new instance is created. This method is
called the class constructor; it initialize the data values in the class.
In [ ]: """
A library book.
"""
class LibraryBook (object):
"""
The self parameter is REQUIRED within the class,
because it tells the program to retrieve/act on the instance object
that called it.
"""
def __init__(self, title, author, pub_year, call_no):
self.title = title
self.author = author
self.year = pub_year
self.call_number = call_no
self.checked_out = False
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 2/9
27/12/2024, 16:39 module4_python
In [ ]: """
Since we have already created my_book as a LibraryBook object,
we could now manually add the title, author,... information associated with
the book.
"""
In [ ]: """
Or we could pass all the information into the __init__ to set up the fields
when creating the new instance.
"""
new_book.author
4.2: Methods
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 3/9
27/12/2024, 16:39 module4_python
In [ ]: class LibraryBook(object):
"""
A library book.
"""
"""
Methods for LibraryBook
"""
# Returns a string representation of the book with it' title and call_n
umber
def __repr__(self):
return "<Book: {} ({})>".format(self.title, self.call_number)
new_book.title_and_author()
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 4/9
27/12/2024, 16:39 module4_python
4.3: Inheritance
In [ ]: class ClownFish(object):
pass
nemo = ClownFish()
In [ ]: type(nemo)
Out[ ]: __main__.ClownFish
In [ ]: isinstance(nemo, ClownFish)
Out[ ]: True
But ClownFish is also a fish, a vertebrate, and an animal, and each could a separate class.
This relationship is called the is-a relationship. It holds between a child class and its parent class. Every class
in Python has at least one parent class.
(Note that the is-a relationship is transitive, so every ClownFish is also an Animal.)
There is a top-most class in Python called object. So far, when we defined classes, we always made object
the direct parent of the class.
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 5/9
27/12/2024, 16:39 module4_python
In [ ]: class Animal(object):
pass
class Vertebrate(Animal):
pass
class Fish(Vertebrate):
pass
class ClownFish(Fish):
pass
class TangFish(Fish):
pass
In [ ]: nemo = ClownFish()
In [ ]: isinstance(nemo, ClownFish)
Out[ ]: True
In [ ]: isinstance(nemo, TangFish)
Out[ ]: False
Out[ ]: True
Out[ ]: True
Every class also has access to the class attributes of the parent class. In particular, methods defined on the
parent class can be called on instances of their "decendants".
In [ ]: class Fish(Animal):
def speak(self):
return "Blub"
class ClownFish(Fish):
pass
class TangFish(Fish):
pass
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 6/9
27/12/2024, 16:39 module4_python
In [ ]: dory = TangFish()
"""
TangFish is a child class of Fish, so it can access the speak() from Fish c
lass.
It will first look for the method call within its class, and if not found,
then repeat
the search for each parent level up.
"""
dory.speak()
Out[ ]: 'Blub'
In [ ]: nemo = ClownFish()
# ClownFish is a child class of Fish, so it can access the speak() from Fis
h class
nemo.speak()
Out[ ]: 'Blub'
What if we want different functionality for a child class? We can override the method (by writing a new one
with the same name).
In [ ]: class TangFish(Fish):
def speak(self):
return "Hello, I'm a TangFish instance."
In [ ]: dory = TangFish()
In [ ]: """
On the other hand, since the ClownFish class still does NOT
define the speak(), instances of ClownFish are still using the
speak() from the parent class of Fish.
"""
nemo = ClownFish()
nemo.speak()
Out[ ]: 'Blub'
When you write your own special method (like str). You are overriding the method of the same name defined
in object.
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 7/9
27/12/2024, 16:39 module4_python
class ClownFish(Fish):
def __init__(self, name):
self.name = name
def __str__(self):
return "A ClownFish named "+self.name
In [ ]: nemo = ClownFish('Nemo')
print(nemo)
In a is-a relationship, the child classe could access the parent class's attributes if not defined in the child
class, or override the attribute value of same attribute exists in the child class.
However, if an instance is defined at one of the parent class levels, then it could NOT access the attributes
that are defined in any of the lower child class level.
In [ ]: class Fish(Vertebrate):
class ClownFish(Fish):
def __init__(self, name):
self.name = name
In [ ]: nemo = ClownFish("nemo")
# The self.name attribute for the __str__() is from the ClownFish class
# but the __str__() is from the Fish class
print(nemo)
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 8/9
27/12/2024, 16:39 module4_python
In [ ]: """
ERROR, because if nemo is an instance of fish class,
then it does NOT have the name attribute.
"""
nemo = Fish()
print(nemo)
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
<ipython-input-33-3dff370cc698> in <module>()
4 """
5 nemo = Fish()
----> 6 print(nemo)
<ipython-input-31-b5476c627494> in __str__(self)
3 # self.name is not defined in Fish class, but is defined in th
e ClownFish class.
4 def __str__(self):
----> 5 return "Hello, my name is {}".format(self.name)
6
7 class ClownFish(Fish):
In [ ]: class Fish(Vertebrate):
def __init__(self, name):
self.name = name
class ClownFish(Fish):
def __init__(self, name):
self.name = name
In [ ]: nemo = ClownFish("Nemo")
In [ ]: nemo = Fish("clown_fish")
In [ ]:
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 9/9