DEV Community

Vera-778
Vera-778

Posted on

Class Inheritance

class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
    def full_name(self):
        return self.first_name + ' ' + self.last_name
    def reverse_name(self):
        return self.last_name + ', ' + self.first_name

class Employee(Person): # Add Person to Employee in brackets, to make it a subclass of Person
    role = None
    def full_name_with_role(self): #add special attributes to the child class, in addition to the attributes get from parent class.
        return self.first_name + ' ' + self.last_name + ', ' + self.role
    def reverse_name(self): #override in child class
        return self.role + ', ' + self.first_name

x = Employee('John', 'Smith')
x.role = 'Director'
print(x.full_name_with_role())
print(x.reverse_name())
Enter fullscreen mode Exit fullscreen mode

Top comments (0)