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
You could create an own method type with a specially crafted __get__()
method.
In this method, you could do something like this:
class combimethod(object):
def __init__(self, func):
self._func = func
def classmethod(self, func):
self._classfunc = classmethod(func)
return self
def __get__(self, instance, owner):
if instance is None:
return self._classfunc.__get__(instance, owner)
else:
return self._func.__get__(instance, owner)
class A(object):
@combimethod
def go(self):
print "instance", self
@go.classmethod
def go(cls):
print "class", cls
a=A()
print "i:",
a.go()
print "c:",
A.go()
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.