This question mentions a hack to differentiate between an instance method (passing self
) and a staticmethod (passing nothing):
class X:
def id(self=None):
if self is None:
# It's being called as a static method
else:
# It's being called as an instance method
(credits to Tom Swirly)
However, this quickly runs into an issue when inheritance comes into play, as the static method has no self
or cls
and therefore cannot call the appropriate method on the message receiver.
My question is, can I do anything like this?
class X:
def get(self_or_cls):
if self_or_cls turns out to be cls:
return self_or_cls.class_method()
else:
return self_or_cls.instance_method()
class Y(X):
foo = str
@classmethod
def class_method(cls):
return cls.foo
def instance_method(self):
return self.foo()
>>> Y.get()
<class 'str'>
>>> Y().get()
''
Any hacks appreciated!