Python class inheritance
- Inheritance is a Python process that allows one class to take on the methods and attributes of another.
- This feature allows users to create more complicated classes that inherit methods or variables from their parent or base classes and makes programming more efficient.
- Inheritance is another way of dealing with laziness (in the positive sense). Programmers want to avoid typing the same code more than once.
- We avoided that earlier by making functions, but now I will address a more subtle problem.
- What if you have a class already, and you want to make one that is very similar? Perhaps one that adds only a few methods? When making this new class, you don’t want to need to copy all the code from the old one over to the new one.
Syntax
class ChildClass(ParentClass):
Example
class Employees(object):
def __init__(self, name, rate, hours):
self.name = name
self.rate = rate
self.hours = hours
staff = Employees(“Wayne”, 20, 8)
supervisor = Employees(“Dwight”, 35, 8)
manager = Employees(“Melinda”, 100, 8)
print(staff.name, staff.rate, staff.hours)
print(supervisor.name, supervisor.rate, supervisor.hours)
print(manager.name, manager.rate, manager.hours)
class Resigned(Employees):
def __init__ (self, name, rate, hours, status):
self.name = name
self.rate = rate
self.hours = hours
self.status = status
exemp_1 = Resigned(“Dorothy”, 32, 8, “retired”)
exemp_2 = Resigned(“Malcolm”, 48, 8, “resigned”)
print(exemp_1.name, exemp_1.rate, exemp_1.hours, exemp_1.status)
print(exemp_2.name, exemp_2.rate, exemp_2.hours, exemp_2.status)
Output
Wayne 20 8
Dwight 35 8
Melinda 100 8
Dorothy 32 8 retired
Malcolm 48 8 resigned