Editor settings

General settings

Save settings

Learn to program with Python

Adding properties and methods to subclass #

If we define new methods or assign new properties in a subclass, those methods and properties will be accessible only in the objects created from that subclass and not the parent. This allows you to extend and customize the functionality of the parent class according to the specific needs of the subclass.

For example:

class Parent:
    def __init__(self):
        self.parent_property = "Parent Property"

class Child(Parent):
    def __init__(self):
        self.parent_property = "Parent Property"
        self.child_property = "Child Property"

    def child_method(self):
        print("This is called from a Child object")

parent = Parent()
child = Child()
print(parent.parent_property)  # Output: Parent Property
print(child.parent_property)  # Output: Parent Property
print(child.child_property)   # Output: Child Property

print(parent.child_property) # AttributeError: 'Parent' object has no attribute 'child_property'

In the example above, both the Parent and Child classes have their own parent_property property, but only the child class has a child_property property. When we try to access child_property in a Parent object, we get an error AttributeError: 'Parent' object has no attribute 'child_property'.

The same is true for methods as well. When we try and call the child_method from a Parent object, we get an error AttributeError: 'Parent' object has no attribute 'child_method'.

child.child_method() # This is called from a Child object
parent.child_method() # AttributeError: 'Parent' object has no attribute 'child_method'

Exercise #

  • Add the property grade and method study to the Student class.

Tests #

  • Person objects should not have the property grade
  • Person objects should not have the method study
  • Student objects should have the property grade
  • Student objects should have the method study
  • The object created from Student("Liam", 13, 7) should have the following properties
    • grade should be 7
    • study() method should print out the message "Liam is a student"
Output will be displayed here