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

Classes in Python

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
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
237 views5 pages

Classes in Python

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
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

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):
self.name = name inf.a = name
self.age = age inf.b = age

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


print("Hello my name is " + self.name) print("Hi my name is", inf.a)

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


p1.age = 40 p1.b=19
print(p1.age) 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):
Self.firstname = fname
Self.lastname = lname

def printname(self):
Print(self.firstname, self.lastname)
#use the person class to create an object and then execute the pritname method:

X= person("koneti","yamini")
X.printname()

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")
X.printname()
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):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

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

x = Student("Mike", "Olsen")
x.printname()
• 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__(fname.lname)
Self.graduationyear = 2023
X= student("mike","olsen")
Print(x.graduationyear)
o/p: 2023
------------------------------------------------------------------------
Code we have:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname) class Person:
def __init__(self, fname, lname):
class Student(Person): self.firstname = fname
def __init__(self, fname, lname): self.lastname = lname
super().__init__(fname, lname)
self.graduationyear = 2019 def printname(self):
print(self.firstname, self.lastname)

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


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

python Page 2
Self.graduationyear = 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)
Self.graduationyear = year
Def welcome(self):
Print("welcome",self.fname,self.lname,"to the class of",self.graduationyear)

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
self.mileage = mileage
# creating an object
obj=vehicle(300,20)
print(obj.max_speed,obj.mileage)

• 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):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
expected output:
Vehicle Name: School Volvo Speed: 180 Mileage: 12
Solution:
class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
class bus(vehicle)
super().__init__(name,max_speed,mileage)
obj=bus("school volvo",10,12)
print("vehicle name: ",obj.name,"speed: ",obj.max_speed,"mileage: "obj.mileage)
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):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


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

python Page 3
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {self.name} 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 capacity.create a child class bus
that inherits from the vehicle class.the 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):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 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):
self.name=name
self.mileage=mileage
self.capacity=capacity

def fare(self):
return self.capacity * 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: ",obj.fare())

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

You might also like