How can you get a not bound class method?
class Foo:
@classmethod
def bar(cls): pass
>>> Foo.bar
<bound method type.bar of <class '__main__.Foo'>>
Edit: This is python 3. Sorry for the confusion.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python 3 does not have unbound methods. Forget about
classmethods for a moment, and look at this:In 2.x, this would be
<unbound method Foo.baz>, but 3.x does not have unbound methods.If you want to get the function out of a bound method, that’s easy:
In the same way:
Things are much more interesting in 2.x, because there actually are unbound methods to get. You can’t normally see an unbound
classmethod, because the whole point is that they get bound to the class at class creation time, instead of being left unbound and then bound to each instance at instance creation time.But really, an unbound method is just any
instancemethodwhoseim_selfis None. So, just as you can do this:Note that
bound_baz.im_funcis the 2.x version ofbound_baz.__func__in 3.x—but thatnew.instancemethoddoes not have a 3.x equivalent.The documentation says that
newis deprecated in favor oftypes, for 3.x compatibility, and in fact, you can do this in 2.x:But that doesn’t work in 3.x, because
MethodTypedoes not take aclassparameter, and does not allow itsinstanceparameter to beNone. And personally, when I’m doing something that is explicitly 2.x-only and cannot be ported to 3.x, I think usingnewis clearer.Anyway, given a class in 2.x, you can do this:
If you print it out, you’ll see:
Or, using your example, with an old-style class:
And yes, maybe it’s a bit of a cheat that the
im_classof aclassmethodfor an old-style class isclassobjeven though that’s notFoo.__class__, but it seems like the most reasonable way to get old-style and new-style classes working similarly in all of the usual use cases.