0% found this document useful (0 votes)
11 views

Python Inheritance

The document explains Python inheritance, where a child class can inherit methods and properties from a parent class. It provides examples of creating a parent class 'Person' and a child class 'Student' that inherits from 'Person'. Additionally, it demonstrates how to add properties to the child class using the 'super()' function.

Uploaded by

MD COMPUTERS
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)
11 views

Python Inheritance

The document explains Python inheritance, where a child class can inherit methods and properties from a parent class. It provides examples of creating a parent class 'Person' and a child class 'Student' that inherits from 'Person'. Additionally, it demonstrates how to add properties to the child class using the 'super()' function.

Uploaded by

MD COMPUTERS
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
You are on page 1/ 1

Python Inheritance

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.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()

Create 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:
Example
Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass
……………………………………………………
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):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()

Add Properties
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):
super().__init__(fname, lname)
self.graduationyear = 2019
x = Student("Mike", "Olsen")
print(x.graduationyear)

You might also like