Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change an instance's method implementation without changing all other instances of the same class? [duplicate]

Tags:

python

I do not know python very much (never used it before :D), but I can't seem to find anything online. Maybe I just didn't google the right question, but here I go:

I want to change an instance's implementation of a specific method. When I googled for it, I found you could do it, but it changes the implementation for all other instances of the same class, for example:

def showyImp(self):     print self.y  class Foo:     def __init__(self):         self.x = "x = 25"         self.y = "y = 4"      def showx(self):         print self.x      def showy(self):          print "y = woohoo"  class Bar:     def __init__(self):         Foo.showy = showyImp         self.foo = Foo()      def show(self):         self.foo.showx()         self.foo.showy()  if __name__ == '__main__':     b = Bar()     b.show()     f = Foo()     f.showx()     f.showy() 

This does not work as expected, because the output is the following:

x = 25

y = 4

x = 25

y = 4

And I want it to be:

x = 25

y = 4

x = 25

y = woohoo

I tried to change Bar's init method with this:

def __init__(self):     self.foo = Foo()     self.foo.showy = showyImp 

But I get the following error message:

showyImp() takes exactly 1 argument (0 given)

So yeah... I tried using setattr(), but seems like it's the same as self.foo.showy = showyImp.

Any clue? :)

like image 569
Thibault Martin-Lagardette Avatar asked Oct 30 '09 01:10

Thibault Martin-Lagardette


People also ask

What is the correct way of creating an instance method?

Calling An Instance Method We use an object and dot ( . ) operator to execute the block of code or action defined in the instance method. First, create instance variables name and age in the Student class. Next, create an instance method display() to print student name and age.

How do you override a class 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.

Can instances have methods Python?

Instance Methods in PythonInstance methods are the most common type of methods in Python classes. These are so called because they can access unique data of their instance.


1 Answers

Since Python 2.6, you should use the types module's MethodType class:

from types import MethodType  class A(object):     def m(self):         print 'aaa'  a = A()  def new_m(self):     print 'bbb'  a.m = MethodType(new_m, a) 

As another answer pointed out, however, this will not work for 'magic' methods of new-style classes, such as __str__().

like image 127
Josh M Avatar answered Sep 18 '22 13:09

Josh M