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
gradeand methodstudyto theStudentclass.
Tests #
Personobjects should not have the propertygradePersonobjects should not have the methodstudyStudentobjects should have the propertygradeStudentobjects should have the methodstudy- The object created from
Student("Liam", 13, 7)should have the following propertiesgradeshould be7study()method should print out the message"Liam is a student"
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules