Creating a Derived Class
Monday February 25, 2008
Python, by default, makes everything an object. When you create a class, it is not actually the first of its kind. Rather, it is a derived class that automatically inherits the attributes and methods of Python's canonical
Simply inheriting from the built-in
object class. This:
class MyClass():
is read by Python as this:
class MyClass(object):
[Note that object is lower-cased. Using caps will return an error.]
Simply inheriting from the built-in
object class, however, leaves little room for any additions or adaptations that you would like to make over a broad number of classes. This comes into play especially if you are creating a library of code to be used in various circumstances. To ammend a pre-existing class, you need to create a new one that inherits from it.
class MyClass():
def MyFunction(self):
print "This is MyFunction in MyClass."
class MySecondClass(MyClass):
pass
myobject = MySecondClass()
myobject.MyFunction()
When you run the above code, the output is as follows:
This is MyFunction in MyClass.In this example,
MySecondClass is the derived class, and MyClass is the base class.
