Creating Subclasses

Subclasses inherits all the attributes and methods of the parent classes and introduce their own.

class child_class(parent_class)
	
	# introuce new attributes using constructor method
	def __init__(self, attribute1,..):
		self.attribute1 = attribute1
		...
	
	# introduce new methods 
	def functionName(self, param1, param2,...):
		# body of function
		...
Important to Note!

When using the The init() Constructor Function in the Child Class, the child class will overwrite the constructor functions and instance variables of the parent class.

To override it, add a call to the parent's __init__() function:

class child_class(parent_class):  
	def __init__(self, attribute1, ...):  
		# call to parent's constructor method
		parent_class.__init__(self, attribute1,...) 
		...
	...

Method Overriding

Description

When a method in a subclass has the:

  • Same name
  • Same parameters
  • Same signature and return type

as the method in its parent class, then the method in the subclass is said to override the method in the parent class.

If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.

class Animal:
    def make_sound(self):
        print("Generic animal sound")

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")

# Create instances
animal = Animal()
dog = Dog()

# Invoke overridden method
animal.make_sound()  # Output: Generic animal sound
dog.make_sound()     # Output: Woof! Woof!
Powered by Forestry.md