0% found this document useful (0 votes)
112 views5 pages

Python Class Inheritance and Examples

Classes in Python allow for creating user-defined objects with properties and methods. The document discusses class definitions, inheritance, and modifying object properties through examples. It shows how to create a parent class called Person with name and age properties and a child class called Student that inherits from Person. Methods like __init__() and printname() are demonstrated. The use of super() to inherit from parent classes is also explained.

Uploaded by

Yamini Koneti
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)
112 views5 pages

Python Class Inheritance and Examples

Classes in Python allow for creating user-defined objects with properties and methods. The document discusses class definitions, inheritance, and modifying object properties through examples. It shows how to create a parent class called Person with name and age properties and a child class called Student that inherits from Person. Methods like __init__() and printname() are demonstrated. The use of super() to inherit from parent classes is also explained.

Uploaded by

Yamini Koneti
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
  • Classes in Python
  • Child Classes in Python
  • Adding Methods
  • Example with Classes
  • Python Programming Tasks

Classes in python

Classes in python
Example for modifing object properties.

class Person: class person:


def __init__(self, name, age): def __init__(inf,name,age):
[Link] = name inf.a = name
[Link] = age inf.b = age

def myfunc(self): def func(inf):


print("Hello my name is " + [Link]) print("Hi my name is", inf.a)

p1 = Person("John", 36) p1 = person("yamini",20)


[Link] = 40 p1.b=19
print([Link]) print(p1.b)
o/p: o/P:
40 19

• class definitions cannot be empty, but if you for some reason have a class definition
with no content, put in the pass statement to avoid getting an error.
• Inheritance allows us to define a class that inherits all the methods and properties
from another class.
• Parent class is the class being inherited from, also called base class.
• Child class is the class that inherits from another class, also called derived class.
Any class can be a parent class, so the syntax is the same as creating any other
class:
Now lets create a parent class.
Asked to create a class named person, with firstname and lastname properties, and a
printname method:

Class person:
def __init__(self,fname,lname):
[Link] = fname
[Link] = lname

def printname(self):
Print([Link], [Link])
#use the person class to create an object and then execute the pritname method:

X= person("koneti","yamini")
[Link]()

Creating a child class:


• To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:

Class student(person)
pass
Now the student class has the same properties and methods as the person class.
Use the student class to create an object and then execute the printname method.

X=student("gamini","royal")
[Link]()
o/P: gamini royal

• So far we have created a child class that inherits the properties and methods from
its parent.
• We want to add the __init__() function to the child class (instead of the pass
keyword).
• When you add the __init__() function, the child class will no longer inherit the

python Page 1
• When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Child class when added the init() function overrides the inherited parent init() function.
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

x = Student("Mike", "Olsen")
[Link]()
• To keep the inheritance of the parent's __init__() function, add a call to the parent's
__init__() function:
• Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:
Class student(person):
Def __init__(self,fname,lname):
Super().__init__(fname,lname)
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.

Add properties:
Adding a property called graduationyear to the student class;

Class student(person):
def __init__(self,fname,lname):
Super().__init__([Link])
[Link] = 2023
X= student("mike","olsen")
Print([Link])
o/p: 2023
------------------------------------------------------------------------
Code we have:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link]) class Person:
def __init__(self, fname, lname):
class Student(Person): [Link] = fname
def __init__(self, fname, lname): [Link] = lname
super().__init__(fname, lname)
[Link] = 2019 def printname(self):
print([Link], [Link])

x = Student("Mike", "Olsen") class Student(Person):


print([Link]) def __init__(self, fname, lname, year):
----------------------------------------------- super().__init__(fname, lname)
Add a year parameter and pass the correct year [Link] = year
when creating the object.
Class student(person): x = Student("Mike", "Olsen", 2019)
Def __init__(self,fname,lname,year): print([Link])
Super().__init__(fname,lname)
[Link] = year

python Page 2
[Link] = year

X=student("mike","olsen",2019)
------------------------------------------------------------------------------
Adding methods:
Add a method called welcome to the student class:
Class student(person):
Def __init__(self,fname,lname,year):
Super().__init__(fname,lname)
[Link] = year
Def welcome(self):
Print("welcome",[Link],[Link],"to the class of",[Link])

Example with classes in python:


• Write a Python program to create a Vehicle class with max_speed and mileage instance
attributes.
class vehicle:
def __init__(self,max_speed,mileage):
self.max_speed = max_speed
[Link] = mileage
# creating an object
obj=vehicle(300,20)
print(obj.max_speed,[Link])

• Create a child class Bus that will inherit all of the variables and methods of the
Vehicle class:
• Given:
class Vehicle:
def __init__(self, name, max_speed, mileage):
[Link] = name
self.max_speed = max_speed
[Link] = mileage
expected output:
Vehicle Name: School Volvo Speed: 180 Mileage: 12
Solution:
class Vehicle:
def __init__(self, name, max_speed, mileage):
[Link] = name
self.max_speed = max_speed
[Link] = mileage
class bus(vehicle)
super().__init__(name,max_speed,mileage)
obj=bus("school volvo",10,12)
print("vehicle name: ",[Link],"speed: ",obj.max_speed,"mileage: "[Link])
Problem 3:
Create a Bus class that inherits from the Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.
Use the following code for your parent Vehicle class.

class Vehicle:
def __init__(self, name, max_speed, mileage):
[Link] = name
self.max_speed = max_speed
[Link] = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {[Link]} is {capacity} passengers"
Expected output:
The seating capacity of a bus is 50 passengers
Solution:
class Vehicle:
def __init__(self, name, max_speed, mileage):
[Link] = name

python Page 3
[Link] = name
self.max_speed = max_speed
[Link] = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {[Link]} is {capacity} passengers"
class bus(Vehicle):
#assign the default value to capacity
def seating_capacity(self,capacity=50):
return super().seating_capacity(capacity=50)
obj=bus("school volvo",180,12)
print(obj.seating_capacity())

Problem 4:
Create a vehicle class with parameters name,mileage and [Link] a child class bus
that inherits from the vehicle [Link] default fare charge of any vehicle is seating
capacity*100. if vehicle is bus isntance, we need to add an extra 10% on full fare as
maintanence charge. So total fare for bus instance will become the final amount= total
fare+10%of total fare.
Note: the bus seating capacity is 50. so the final fare amount must be 5500. you need to
override the fare() method of a vehicle class in a bus class.
Use the following code for your parent vehicle class. We need to access the parent class
from inside a method of a child class.

class Vehicle:
def __init__(self, name, mileage, capacity):
[Link] = name
[Link] = mileage
[Link] = capacity

def fare(self):
return [Link] * 100

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

Expexted output: total bus fare is: 5500.

Solution:
class vehicle:
def __init__(self,name,mileage,capacity):
[Link]=name
[Link]=mileage
[Link]=capacity

def fare(self):
return [Link] * 100

class bus(vehicle):
def fare(self):
amount=super().fare()
amount+=amount*10/100
return amount
obj= bus("school volvo",12, 50)
print("total bus fare is: ",[Link]())

Problem 5:
Write a program to iterate the first 10 numbers and in each iteration, print the sum of
the current and previous number.
Solution:

python Page 4
Solution:
print("Printing current and previous number and their sum in a range(10)")
previous_num = 0

# loop from 1 to 10
for i in range(1, 11):
x_sum = previous_num + i
print("Current Number", i, "Previous Number ", previous_num, " Sum: ", previous_num +
i)
# modify previous number
# set it to the current number
previous_num = i

Problem5:
Write a program to accept a string from the user and display characters that are present
at an even index number.

For example, str = "pynative" so you should display ‘p’, ‘n’, ‘t’, ‘v’.
Solution:
word= input('enter the word: ')
print('the word: ',word)
print("priting only even indexed letters in the word.")
length=len(word)
for i in range (0,length-1,2):
print(word[i])
# function
def myfunc(word):
length = len(word)
for i in range(0,length,2):
print(word[i])
# driver module
word = "yamini"
print("the original word: ",word)
print(myfunc(word))

python Page 5

Common questions

Powered by AI

Abstracting common attributes using a parent class, as in the Vehicle-Bus example, promotes code reusability and maintainability. Common attributes and methods defined in the Vehicle parent class, such as name, max_speed, and mileage, encapsulate shared behaviors and properties, reducing redundancy. This structure facilitates easier updates and extensions to related subclasses, fostering a cleaner, more organized codebase that can be easily extended with new subclasses like Car or Truck .

User-defined class constructors, defined using __init__, directly initialize object properties during the creation of a class instance. This mechanism allows for the flexible setup of initial values and enables the inclusion of necessary setup logic, ensuring that all instances can start with pre-configured, consistent properties as seen with the Person and Vehicle classes .

Adding an __init__() method to a child class essentially overrides the inherited __init__() method from its parent class, which means the parent class's initialization logic will not be executed. To manage this and ensure that the properties and methods of the parent class are still initialized appropriately, the super() function should be used within the child's __init__() method. This will explicitly call the parent class's __init__() method, preserving the inheritance hierarchy while allowing custom initialization logic .

Default parameter values in method definitions in Python provide flexibility by allowing methods to be called with fewer arguments than they can accept. This is demonstrated in the Bus class where the seating_capacity method has a default value of 50 passengers if no argument is provided, simplifying the interface for users who do not need to specify the capacity explicitly and ensuring a consistent behavior when that detail is not crucial .

Inheritance in Python allows a Student class to extend the Person class, inheriting attributes like firstname and lastname, and methods such as printname. This shows method sharing, where the Student can use the Person's printname method without redefining it. Additionally, the Student class can extend functionality by adding new attributes like graduationyear or new methods like welcome. This inheritance model simplifies code and promotes reuse, allowing for hierarchical structuring of related classes .

It is important to override the fare method in the Bus subclass to implement specific logic concerning fare calculation that differs from the base Vehicle class. In the example, buses have an additional maintenance charge of 10% on the base fare, which requires custom behavior not present in the general Vehicle fare method. This distinction is crucial for accurately modeling real-world scenarios where different vehicle types have different costing structures .

The pass statement is significant in Python because it acts as a placeholder in class definitions where no content is currently available. It prevents errors when a class initially does not define any methods or properties. It should be employed when a class blueprint is necessary for the structure of the code, but its implementation details are yet to be decided or are temporarily omitted .

Overriding methods in Python allows subclass implementations to provide specific behavior not present in base classes. In the context of calculating 'fare' in a Bus class, overriding allows the Bus class to add an additional maintenance charge to the base fare calculated in the parent Vehicle class. This demonstrates how subclass-specific logic, such as adding 10% to the fare for buses, can be effectively managed without altering the parent class method .

The super() function allows a child class to call the parent class's __init__() method, maintaining the inheritance while also allowing the child class to initialize additional properties. When using super(), it enables the child class to automatically inherit all the methods and properties from its parent, without explicitly referring to the parent class by name .

Python is case-sensitive; hence, class and method names must be referenced exactly as declared. For example, using different casing such as 'Class' instead of 'class' or 'Function' instead of 'function' will result in errors or unexpected behavior. Proper capitalization conventions, such as capitalized names for classes and lowercase for methods, enhance code readability and adhere to Python's community standards .

Classes in python
Example for modifing object properties.
class Person:
def __init__(self, name, age):
    self.name = name
When you add the __init__() function, the child class will no longer inherit the 
parent's __init__() function.
•
Child class
Self.graduationyear = year
X=student("mike","olsen",2019)
-------------------------------------------------------------------
self.name = name
        self.max_speed = max_speed
        self.mileage = mileage
    def seating_capacity(self, cap
Solution:
print("Printing current and previous number and their sum in a range(10)")
previous_num = 0
# loop from 1 to 10
for

You might also like