method that can be called from a class and also from an instance
Marc Aymerich
glicerinu at gmail.com
Thu Nov 22 11:34:56 EST 2012
On Thursday, November 22, 2012 5:26:59 PM UTC+1, Dave Angel wrote:
> 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.
>
thanks for the links Thomas and Dave, I'm going to read this documentation right now, I love to learn this kind of python 'internals' :)
More information about the Python-list
mailing list