On 11/22/2012 11:12 AM, Thomas Bach wrote: > 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>
OK, thanks. I hadn't tried it, and hadn't noticed that that decorator converts to the class. > > 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 > The OP should probably use this link instead, since he's not using Python 3. http://docs.python.org/2.7/howto/descriptor.html Marc: I believe the descriptor stuff has changed in Python 3; I don't use it. But if you've got to do this, and you have to do it in Python 2.x, you'd better use the 2.x documentation. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list