method that can be called from a class and also from an instance

Thomas Bach thbach at
Thu Nov 22 17:12:42 CET 2012

On Thu, Nov 22, 2012 at 10:52:56AM -0500, Dave Angel wrote:
> On 11/22/2012 10:14 AM, Marc Aymerich wrote:
> > I want to create a method within a class that is able to accept either a class or an instance.
> >
> I haven't tried it, but how about if you do a @classmethod decorator,
> and then just use isinstance(param, MyClass) ?

This won't work:

In [22]: class Foo(object):
   ....:     @classmethod
   ....:     def bar(cls):
   ....:         print repr(cls)

In [23]:
<class '__main__.Foo'>

In [24]: Foo().bar()
<class '__main__.Foo'>

Actually help(classmethod) explicitly says so:
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()).  The instance is ignored except for its class.

I think the way to go is via the descriptor protocol[1] as suggested
by Peter.



More information about the Python-list mailing list