I want to assign a callable class as a function on another class, and then reference the owner class from the owned function:
class DoIt(object):
def __call__(self):
print "%s did it" % self.name
class Doer(object):
def __init__(self, name):
self.name = name
doSomething = DoIt()
doer = Doer("Bob")
doer.doSomething()
In the code above, I want the doSomething() function to print “Bob did it”, but with this code I’ll get a
AttributeError: ‘DoIt’ object has no attribute ‘name’
Because self references the DoIt instance, not the Doer instance. Is it possible to reference the Doer instance?
Explanation: (This is the asker explaining this answer as best he can)
Python offers you descriptor classes, which are classes that act as attributes (in contrast to attributes as instance variables or properties). The
__get__method of a descriptor class dictates what’s returned when that class is assigned and accessed as an attribute on another class. And__get__lets you access both the owning instance and owning class (See method signature).By having
__get__return a function, you essentially create a callable that has access to its owner.For more on descriptors, see Attributes, Properties and Descriptors- Building Skills in Python