[Tutor] who called the class method?
kent37 at tds.net
Tue Jun 21 21:25:33 CEST 2005
David Driver wrote:
> Is there a way to test if a class method was called from an instance?
> What I am trying to do is if a method is called from the class return
> a commanding proxy with an mock or stub type object as the proxied
> object. If it is called from the instance I want to return a proxy for
> the instance.
Hmm. Why not just differentiate them at the point of call? If you want to do
instead of t.foo() and T.foo() use t.foo_from_instance() and T.foo_from_class()??
If you must, I can think of two ways to do this. The __get__() method of a property has an instance parameter which is the instance or None, you could use that. Or you can use __new__() to create an instance method that shadows the classmethod.
''' A descriptor for Test2.foo '''
def __get__(self, instance, owner):
# Test2.foo returns a function
foo = _foo()
def fooImpl(cls, instance):
print 'fooImpl called with instance =', instance
t = Test2()
print 'foo() called from an instance'
instance = object.__new__(cls)
instance.foo = new.instancemethod(foo, instance, Test)
print 'foo() called as a classmethod'
t = Test()
If you ask on comp.lang.python you will probably get more clever answers but really, why do you need to do this?
More information about the Tutor