Adding custom methods to sub-classes in Python – An Example
class Animal(object): name = None def speak(self): print'My name is ', self.name def walk(self): print "I don’t know how to walk" def breath(self): print "I don’t know how to breath" class Dog(Animal): breed = None def speak(self): print 'Woof!!' def whatbreed(self): Print "I am a ", self.breed fido = Dog() fido.breed = 'pug' fido.whatbreed()
Output: I am a pug
Note that the whatbreed() class has been added to the subclass Dog() but is not present in the base class Animal(). Only instances of the Dog() class can access this method.