I have some code which I would like to pass instances or classes interchangeably. All I will do in that code is to call a method that I expect both classes and instances to have (the method go()
in the example below).
Unfortunately, I can't create a classmethod with the same name of a regular method... See example below. I initially expected the second call to produce an a
instead of a b
.
Any advice on how to achieve this?
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def go(self):
... print "a"
... @classmethod
... def go(cls):
... print "b"
...
>>> a=A()
>>> a.go()
b
>>> A.go()
b
Consider reusing the
classinstancemethod
decorator from formencode.https://bitbucket.org/formencode/official-formencode/src/06d52c5b33c9/formencode/declarative.py
You could create an own method type with a specially crafted
__get__()
method.In this method, you could do something like this:
NOTE: The above is not very thoroughly tested, but seems to work. Nevertheless, it should be seen as a kind of "solution-near pseudo-code", not as a solution. It should give you an idea how to achieve your goal.
How about something like: