0% found this document useful (0 votes)
18 views11 pages

Python - 5

The document explains the concepts of object methods and class methods in Python, highlighting their definitions, syntax, and usage through examples. It also covers inheritance in object-oriented programming, detailing types such as single, multiple, multilevel, hierarchical, and hybrid inheritance, along with practical examples. Additionally, it includes assignment tasks for practical application of the discussed concepts.

Uploaded by

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

Python - 5

The document explains the concepts of object methods and class methods in Python, highlighting their definitions, syntax, and usage through examples. It also covers inheritance in object-oriented programming, detailing types such as single, multiple, multilevel, hierarchical, and hybrid inheritance, along with practical examples. Additionally, it includes assignment tasks for practical application of the discussed concepts.

Uploaded by

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

Object Method and Class Method

1. Object Method (Instance Method)


Definition: An object method (or instance method) operates on an instance of the
class. It can access and modify instance-specific attributes and call other instance
methods. It also has access to class attributes.
Syntax: Defined using the def keyword inside a class and takes self as its first
parameter, which refers to the instance.
class Student:
school = "Chavara School"

def __init__(self, name, age):


[Link] = name
[Link] = age

def display(self):
print("Name:", [Link])
print("Age:", [Link])
print("School:", [Link])

st1 = Student("Alwin", 20)


[Link]()

st2 = Student("David", 21)


[Link]()
Explanation:

display is an object method that prints instance-specific data (name and age) and
the class attribute (school).
The method is called on instances st1 and st2 of the Student class.

2. Class Methods
Definition: Class methods operate on the class itself rather than on instances. They
can access and modify class-level attributes and are defined using the
@classmethod decorator. They take cls as their first parameter, which refers to the
class.

1. Accessing Class Variable Without Creating an Object


class Student:
school = "Chavara School"
@classmethod
def print_school(cls):
print('School Name:', [Link])

Student.print_school()
Explanation:

print_school is a class method that prints the class attribute school.


It can be called directly on the class (Student.print_school()) without needing to
create an instance.

2. Creating an Object Using Class Method


In Python, a decorator is a design pattern that allows you to modify or extend the
behavior of functions or methods without changing their code.
The @classmethod decorator is used to define a method that is bound to the class
and not the instance of the class.
Example:
class Student:
school = "Chavara School"

def __init__(self, name, age):


[Link] = name
[Link] = age

def display(self):
print("Name:", [Link])
print("Age:", [Link])
print("School:", [Link])

@classmethod
def create_object_from_birth_year(cls, name, birth_year):
age = 2024 - birth_year
return cls(name, age)

st3 = Student.create_object_from_birth_year('Amal', 1998)


[Link]()
Explanation:
create_object_from_birth_year is a class method that creates a Student object
based on the provided name and birth_year.
It calculates the age and returns an instance of the class (cls(name, age)).
The method is called on the class Student to create st3 and initialize it.
Object Method: Operates on instance data and can access class attributes.
Requires an instance of the class to be called.
Class Method: Operates on class-level data and can access or modify class
attributes. Can be called directly on the class itself, without creating an instance.

Class -Assignment Tasks


1. Define a Python class called Course with attributes course_name and
duration. How do you create an object and print its details?
2. Write a Python class BankAccount with attributes account_number and
balance. How do you create an object and access its balance attribute?
3. Create a Python class Counter with a class variable count and an instance
method increment(). How do you define the method to increase both the
instance and class variable count?
4. Create a Python class School with a class variable total_students and instance
variables name and location. How do you define a method that updates
total_students based on the number of students added?

3. Data Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a new class to inherit properties and behaviors (methods) from an existing
class. The existing class is called the parent class (or superclass), and the new
class is called the child class (or subclass).

1. Basic Inheritance:

class Person:
def greet(self):
print("Hi, I am Person")

class Student(Person):
def display(self):
print("Hi, I am Student")

st1=Student() # creating object for child


[Link]() # accessing method of parent using child object
[Link]() # accessing parent method using child object

2. Constructor Inheritance:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def greet(self):
print("Hi, I am Person")

class Student(Person):
def display(self):
print("Name:", [Link])
print("Age:", [Link])
print("Hi, I am Student")

st1 = Student("Amal", 21)


[Link]()

3. Constructor Overriding:

class Person:
def __init__(self):
print("Person class init method is called")

def greet(self):
print("Hi, I am Person")

class Student(Person):
def __init__(self):
print("Student class init method is called") #
constructor overriding

def display(self):
super().greet()
print("Hi, I am Student")

st1=Student() # class Student class init method

4. Using super() and super().__init__:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def greet(self):
print("Hi, I am Person")

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
#Person.__init__(self, name, age)
self.student_id = student_id

def display(self):
super().greet()
print("Name:", [Link])
print("Age:", [Link])
print("Student Id:", self.student_id)

st1 = Student("Amal", 22, 1)


[Link]()

5. Method Overriding:
Method overriding is a feature in object-oriented programming that allows a
subclass to provide a specific implementation of a method that is already defined in
its superclass. When a method in a subclass has the same name, return type, and
parameters as a method in its superclass, the method in the subclass overrides the
one in the superclass.

class Person:
def greet(self):
print("Hi, I am Person")

class Student(Person):
# def greet(self):
# print("Hi, I am Student")

st1 = Student()
[Link]() # Outputs: "Hi, I am Student" unless the method
is overridden

Types of Inheritance
1. Single Inheritance:

● Single inheritance involves one subclass inheriting from a single


superclass.
● It forms a simple parent-child relationship.

Example
class Person:
def greet(self):
print("Hi, I am Person")

class Student(Person):
def display(self):
print("Hi, I am Student")

st1=Student() # creating object for child


[Link]() # accessing method of parent using child object
[Link]() # accessing parent method using child object

2. Multiple Inheritance:

● Multiple inheritance involves a subclass inheriting from multiple


superclasses.
● It allows a subclass to inherit attributes and methods from multiple
sources.
1. Example - instance method

class A:
def display(self):
print('Class A')
class B:
def display(self):
print('Class B')
class C(A,B):
def display(self):
print('Class C')
obj=C()
[Link]()
print([Link]()) # to check MRO

Method Resolution Order (MRO) determines the order in which Python searches
for methods in the inheritance hierarchy.
Classes Involved in above example: C, B, A
MRO Order: The MRO of above example [C -> A -> B]
Syntax: [Link]()
In Python, object is the most basic built-in class and is the ultimate base class for
all classes. object is the root of the class hierarchy. When you define a new class
without specifying a parent class, it automatically inherits from [Link] is why
you see class 'object' at the end of the Method Resolution Order (MRO).
class A:
pass
It is equivalent to:
class A(object):
pass

2. Example - instance variable


class A:
def __init__(self):
print('Class A')
class B:
def __init__(self):
print('Class B')
super().__init__()
class C(B,A):
# def __init__(self):
# print('Class C')
pass
obj=C()
print([Link]())

3. Multilevel Inheritance:

● Multilevel inheritance involves a chain of inheritance with each


subclass inheriting from its superclass.
class A:
def __init__(self):
print('Class A')
class B(A):
def __init__(self):
print('Class B')
super().__init__()
class C(B):
def __init__(self):
print('Class C')
super().__init__()
obj = C()

4. Hierarchical Inheritance:
Hierarchical inheritance involves multiple subclasses inheriting from a single
superclass.

class A:
def __init__(self):
print('Class A')

class B(A):
def __init__(self):
print('Class B')
super().__init__()

class C(A):
def __init__(self):
print('Class C')
super().__init__()

# Create instances of B and C


obj_b = B()
print() # Just for spacing
obj_c = C()

5. Hybrid (or Mixed) Inheritance:


● Hybrid inheritance combines different types of inheritance, such as single,
multiple, or hierarchical inheritance.
class A:
def __init__(self):
print('Class A')
class B(A):
def __init__(self):
super().__init__()
print('Class B')
class C(A):
def __init__(self):
super().__init__()
print('Class C')
class D(B, C):
def __init__(self):
super().__init__()
print('Class D')

# Create an instance of D
obj_d = D()

Tasks - Assignment

1. Define a base class Employee with an instance variable salary and a


method show_salary(). Create a derived class Manager that overrides
salary and adds an additional bonus. Show how the show_salary()
method behaves with overridden values.
2. Create a Vehicle class with attributes make and model. Then create a Car class
that inherits from Vehicle and has an additional attribute number_of_doors.
Write a method to display all the details of a car.
3. Define two base classes Person and Employee. The Person class should
have an attribute name, and the Employee class should have an attribute
employee_id. Create a derived class Manager that inherits from both
Person and Employee, and implements a method to display the name and
employee_id.

You might also like