In python, a class instance can be used almost like a function, if it has a __call__
method. I want to have a class B
that has a method A
, where A
is the instance of a class with a __call__
method. For comparison, I also define two other methods foo
and bar
in the "traditional" way (i.e. using def
). Here is the code:
class A(object):
def __call__(*args):
print args
def foo(*args):
print args
class B(object):
A = A()
foo = foo
def bar(*args):
print args
When I call any of the methods of B
, they are passed a class instance as implicit first argument (which is conventionally called self
).
Yet, I was surprised to find that b.A()
gets passed an A
instance, where I would have expected a B
instance.
In [13]: b = B()
In [14]: b.A()
(<__main__.A object at 0xb6251e0c>,)
In [15]: b.foo()
(<__main__.B object at 0xb6251c0c>,)
In [16]: b.bar()
(<__main__.B object at 0xb6251c0c>,)
Is there a way (maybe a functools
trick or similar) to bind A()
in such a way that b.A()
is passed a reference to the b
object?
Please note that the example presented above is simplified for the purpose of illustrating my question. I'm not asking for advice on my actual implementation use case, which is different.
Edit: I get the same output, if I define my class B
like this:
class B(object):
def __init__(self):
self.A = A()
foo = foo
def bar(*args):
print args