[Tutor] who called the class method?

Kent Johnson 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
class T(object):
  @classmethod
  def foo(cls):
    pass

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. 


class Test2(object):
    class _foo(object):
        ''' A descriptor for Test2.foo '''
        def __get__(self, instance, owner):
            # Test2.foo returns a function
            def _fooImpl():
                Test2.fooImpl(instance)
            return _fooImpl
    
    foo = _foo()
    del _foo
    
    @classmethod
    def fooImpl(cls, instance):
        print 'fooImpl called with instance =', instance

t = Test2()
t.foo()
Test2.foo()


import new

class Test(object):
    def __new__(cls):
        def foo(self):
            print 'foo() called from an instance'
        instance = object.__new__(cls)
        instance.foo = new.instancemethod(foo, instance, Test)
        return instance
        
    @classmethod
    def foo(cls):
        print 'foo() called as a classmethod'


t = Test()
t.foo()
Test.foo()


If you ask on comp.lang.python you will probably get more clever answers but really, why do you need to do this?

Kent



More information about the Tutor mailing list