Explain Inheritance vs Instantiation for Python classes.


Inheritance

Being an Object Oriented language, Python supports inheritance, it even supports multiple inheritance. Classes can inherit from other classes. A class can inherit attributes and behaviour methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. In other words inheritance refers to defining a new class with little or no modification to an existing class.

class A:        # define your class A
pass
class B:         # define your class B
pass
class C(A, B):   # subclass of A and B

Instantiation

Instantiating a class is creating a copy of the class which inherits all class variables and methods. Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines. The return value will be the newly created object.

Example

class Foo():
        def __init__(self,x,y):
            print x+y
f = Foo(3,4)

Output

7

Updated on: 09-Sep-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements