P 3 Python 1
P 3 Python 1
Programming)
• Python Classes/Objects
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and
methods.
• A Class is like an object constructor, or a "blueprint" for creating
objects.
• Create a Class
• To create a class, use the keyword class:
• Example
• Create a class named MyClass, with a property named x:
• class MyClass:
• x=5
• Create an object named p1, and print the value of x:
• p1 = MyClass()
print(p1.x)
The __init__() Function
• The examples above are classes and objects in their simplest form, and
are not really useful in real life applications.
• To understand the meaning of classes we have to understand the built-in
__init__() function.
• All classes have a function called __init__(), which is always executed
when the class is being initiated.
• Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
• The __init__() function is called automatically every time the class is
being used to create a new object.
• Create a class named Person, use the __init__() function to assign
values for name and age:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
The __str__() Function
• The __str__() function controls what should be returned when the
class object is represented as a string.
• If the __str__() function is not set, the string representation of the
object is returned:
• The string representation of an object WITH the __str__() function:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Object Methods
• Objects can also contain methods. Methods in objects are functions that belong to
the object.
• Insert a function that prints a greeting, and execute it on the p1 object:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self Parameter
def display_info(self):
print(f"Brand: {self.brand}, Model: {self.model}, Year: {self.year}")
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Department: {self.department}")
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
@property
def age(self):
return self.__age
# Property setter for modifying the age (mutator)
@age.setter
def age(self, age):
if age > 0:
self.__age = age
else:
print("Invalid age. Age must be positive.")
# Creating an object of the Person class
person = Person(25)
print("Current age:", person.age)
# Modifying the age using the property setter
person.age = 30
print("Updated age:", person.age) # Output: Updated age: 30
• class Student(Person):
• def __init__(self, fname, lname):
• #add properties etc.
• The child's __init__() function overrides the inheritance of the
parent's __init__() function.
• To keep the inheritance of the parent's __init__() function, add a call
to the parent's __init__() function:
• Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
• Use the super() Function
• Python also has a super() function that will make the child class inherit
all the methods and properties from its parent:
• By using the super() function, you do not have to use the name of the
parent element, it will automatically inherit the methods and properties
from its parent.
• Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
• Add Properties
• Example
• Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
• Add Method
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
• If you add a method in the child class with the same name as a
function in the parent class, the inheritance of the parent method will
be overridden.
• Polymorphism in Python refers to the ability to define methods that are
common across multiple classes, allowing different objects to respond to
the same method in their own way. Polymorphism is a core concept in
object-oriented programming (OOP) and allows code reusability and
flexibility.
• Types of Polymorphism:
• Compile-time polymorphism (Method Overloading): Not directly
supported in Python (handled using default arguments).
• Runtime polymorphism (Method Overriding): Achieved by defining
methods with the same name in different classes, and Python uses the
method that belongs to the object type at runtime.
Python Polymorphism
• The word "polymorphism" means "many forms", and in programming
it refers to methods/functions/operators with the same name that
can be executed on many objects or classes
• Function Polymorphism
• An example of a Python function that can be used on different objects
is the len() function.
# len() works on both strings and lists
print(len("Hello")) # Output: 5
print(len([1, 2, 3, 4])) # Output: 4
Example of Polymorphism using
Method Overriding:
• class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
# Abstract class
class Animal(ABC):
@abstractmethod
def make_sound(self):
"""Abstract method: must be implemented in subclasses."""
pass
def sleep(self):
"""Concrete method: common to all animals."""
print("This animal is sleeping.")
• The try block lets you test a block of code for errors.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
• Example
• The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Many Exceptions
• You can define as many exception blocks as you want, e.g. if you want
to execute a special block of code for a special kind of error:
Else
• You can use the else keyword to define a block of code to be executed if no
errors were raised:
• Example
• In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
if x < 0:
raise Exception("Sorry, no numbers below zero")
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the
user.
x = "hello"