Reputation: 927
Say I have a class Foo
and I do foo = Foo()
. I want some kind of "method namespace" foo.bar
that is not shared across Foo
instances, to which I dynamically can add methods that operate on foo
:
def method(self, someValue):
self.value = someValue + 10
foo.bar.m = method
foo.bar.m(20)
And then I want to find that foo.value
is 30.
Any way to accomplish this?
Upvotes: 2
Views: 380
Reputation: 64068
Is this what you're looking for?
import types
class Namespace(object):
pass
class Foo(object):
def __init__(self, value):
self.value = value
self.bar = Namespace()
def function(self, new_value):
self.value = new_value
a = Foo(1)
b = Foo(2)
b.bar.function = types.MethodType(function, b, Foo)
b.bar.function(6)
print a.value # prints 1
print b.value # prints 6
The trick is using the types
module to convert the test function into a method that can be bound to an instance of the object.
When I run this line: b.bar.function = types.MethodType(function, b, Foo)
, I am essentially telling Python to create a new method that binds function
to the b
instance of Foo
. I can then take this method and store it inside any arbitrary location.
Since the method is permanently bound to the b
instance of Foo
, self
will always refer to b
regardless of which object the method is actually assigned to.
Upvotes: 3