Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a method at instance level

Tags:

python

Is there a way in Python to override a class method at instance level? For example:

class Dog:     def bark(self):         print "WOOF"  boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE boby.bark() # WoOoOoF!! 
like image 619
pistacchio Avatar asked Dec 27 '08 07:12

pistacchio


People also ask

How do you override a base class method in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

What is method overriding in Python?

Method overriding in Python is when you have two methods with the same name that each perform different tasks. This is an important feature of inheritance in Python. In method overriding, the child class can change its functions that are defined by its ancestral classes.

How do you overwrite an object in Python?

In python what we call variables are really labels referring to objects. So if you want to change an object that is not immutable (like a list), that should work out-of-the-box in Python. However, you cannot really generally overwrite objects in Python. Creating a new object will use free memory.


1 Answers

Yes, it's possible:

class Dog:     def bark(self):         print "Woof"  def new_bark(self):     print "Woof Woof"  foo = Dog()  funcType = type(Dog.bark)  # "Woof" foo.bark()  # replace bark with new_bark for this object only foo.bark = funcType(new_bark, foo, Dog)  foo.bark() # "Woof Woof" 
like image 71
codelogic Avatar answered Sep 23 '22 00:09

codelogic