Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
What is Inheritance? | Inheritance
In-Depth Python OOP
course content

Зміст курсу

In-Depth Python OOP

In-Depth Python OOP

1. OOP Concepts
2. Inheritance
3. Encapsulation
4. Polymorphism and Abstraction
5. Magic Methods

What is Inheritance?

In Python, inheritance is one of the fundamental concepts of object-oriented programming (OOP). It refers to the ability of a subclass to inherit properties and behaviors (i.e., methods and attributes) from a parent class. Inheritance allows for code reuse and helps to create a hierarchical structure of classes, where subclasses can specialize or extend the functionality of their parent classes.

To inherit a subclass from another class, you can write its name in parentheses () after the subclass name (without space):

1234567
class User: role = "User" class Staff(User): pass print(Staff.role)
copy

This code demonstrates that child classes can access attributes from their parent classes, allowing them to use or override them as needed.

Note

The interpreter searches attributes from the Child to the last Parent in order.

Look at the code example:

123456789101112131415161718
class User: role = "User" def __init__(self, name): self.name = name def print_name(self): print(f"Is a {self.role} with the name {self.name}") class Staff(User): pass bob = Staff("Bob") bob.print_name() # takes `print_name()` from the `User` class print(bob.role) # takes `role` from the `User` class
copy

The code then accesses the role attribute of the bob instance using bob.role. Since the role attribute is not defined in the Staff class or the bob instance, it falls back to the role attribute of the User class, and "User" is printed.

In summary, this code demonstrates how class attributes can be inherited and accessed by instances, as well as how instance attributes are unique to each instance.

123456789101112131415161718
class User: role = "User" def __init__(self, name): self.name = name def print_name(self): print(f"Is a {self.role} with the name {self.name}") class Staff(User): role = "Staff" bob = Staff("Bob") bob.print_name() # takes `print_name()` from the `User` class print(bob.role) # takes `role` from the `Staff` class
copy

Similarly, when print(bob.role) is called, it accesses the role attribute from the Staff class, which has overridden the role attribute from the User class. As a result, it will output "Staff".

Все було зрозуміло?

Секція 2. Розділ 1
We're sorry to hear that something went wrong. What happened?
some-alt