AgerNic.com
WEB DEVELOPER SITE, HTML, CSS, PHP, SQL

Python Inheritance


Python Tutorial » Python Inheritance

Inheritance allows to define a class that inherits all the methods and properties from another class.
Inheritance is a powerful feature in object oriented programming.
1. Base or Parent class.
2. Derived or Child class.

Create Base or Parent class


Create a class named Town, with town_name and town_population properties, and a printname method:

Example:
class Town:
  def __init__(self, town_name, town_population):
    self.town_n = town_name
    self.town_p = town_population

  def printname(self):
    print(self.town_n, self.town_p)

#Use the Town class to create an object, and then execute the printname method:

x = Town("London with", "12000 K")
x.printname()

Output: London with 12000 K


Derived or Child class

Create a class named capital_of_country, which will inherit the properties and methods from the Town class:

Example:
# ****** Derived or Child class *********
class Town:
  def __init__(self, town_name, town_population):
    self.town_n = town_name
    self.town_p = town_population

  def printname(self):
    print(self.town_n, self.town_p)

class capital_of_country(Town):
  pass

y = Town("London, GB capital with", "12000 K")
y.printname()


#********* Create Base or Parent class *************
class Town:
  def __init__(self, town_name, town_population):
    self.town_n = town_name
    self.town_p = town_population

  def printname(self):
    print(self.town_n, self.town_p)

#Use the Town class to create an object, and then execute the printname method:

y = Town("London with", "12000 K")
y.printname()
Output:
London, GB capital with 12000 K
London with 12000 K




python inheritance vs composition, super, override method, constructor, multiple classes, init, classes, function override, order
Python Inheritance - python

Online Editor
ONLINE EDITOR

news templates


COLOR PICKER

news templates
This tool makes it easy to create, adjust, and experiment with custom colors for the web.


HTML Templates
news templates
Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.


CSS HTML Layout
news templates
Find here examples of creative and unique website layouts.


Free CSS HTML Menu
news templates
Find here examples of creative and unique website CSS HTML menu.


0
Online Editor
ONLINE EDITOR

news templates


COLOR PICKER

news templates
This tool makes it easy to create, adjust, and experiment with custom colors for the web.


HTML Templates
news templates
Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.


CSS HTML Layout
news templates
Find here examples of creative and unique website layouts.


Free CSS HTML Menu
news templates
Find here examples of creative and unique website CSS HTML menu.