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]: Foo.bar()
<class '__main__.Foo'>

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

Actually help(classmethod) explicitly says so:
<quote>
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.
</quote>

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

Regards,
        Thomas.


Footnotes: 
[1] http://docs.python.org/3/howto/descriptor.html

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to