Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
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):
class User: role = "User" class Staff(User): pass print(Staff.role)
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:
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
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.
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
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".
Дякуємо за ваш відгук!