Thursday, May 29. 2008Python Brain-TeaserTrackbacks
Trackback specific URI for this entry
No Trackbacks
Comments
Display comments as
(Linear | Threaded)
x.get_me.im_class For me he expects that x is class Bar and not from class Foo : ) a good way to do it is: def get_me(self): return self.me class Foo: me = "foo" class Bar: me = "bar" def get_me(self): return self.me Foo.get_me = get_me and maybeBar.get_me = get_me For keep everything the same.x = Foo() print x.get_me()
The error produced by this code comes from the differences between bound methods, unbound methods and functions. Bar.get_me is an instancemethod; such objects know the class they’re defined in. You cannot assign a method from a class to another: A method knows which objets it accepts, and since Foo is not a subclass of Bar in your example, Bar.get_me can’t work with Foo instances. However, you can dynamically assign methods to a class, using function objects: >>> Foo.get_me = Bar.get_me.im_func >>> Foo().get_me() 'foo' The “self” name is not magic at all, you understood right. “getattr(Bar(), 'get_me')()” (the same thing as “Bar().get_me()”, really) works because “thing.method()” is equivalent to “ThingClass.method(thing)”. Hope this helps Cheers |
QuicksearchArchivesLinksCategories |