Skip to content

Redefining Class Methods in Python

Lets say we have a simple animal class:

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"

And we can create an instance based on this class:

dog = Animal()
dog.name = 'bingo'
dog.speak
Output: My name is bingo

Great! But what if we want this dog to ‘Woof!’ rather than announce its name?, we would redefine the class but still use Animal() as our base class:

class Dog(Animal):
  
  def speak(self):
    Print 'Woof!!'

Now we can create an instance variable based on this new Dog() class:

fido = dog()
fido.speak()
Output: Woof!!

Lets see this code all put together:

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):

  def speak(self):
    print'Woof!!'

fido = Dog()
fido.speak()
Output: Woof!!

NOTE: Any methods that we didn’t override in the Dog() class will fall back to the base Animal() class.

If we were to run:

Fido.walk()

Or

Fido.breath()

We would get the strings defined in the methods in the Animal() Class because we did not redefine them in our new Dog() class:

fido.walk()
Output: I don't know how to walk
fido.breath()
Output: I don't know how to breath
Published inPyCharmPythonscripting