I was curious whether Python allowed both a bound and unbound version an otherwise identically named method within a class e.g.
class Bounds(object):
def __init__(self):
pass
def method(self):
print('I am a bound method')
@staticmethod
def method():
print('I am an unbound method free of the class instance!')
I wish to do something like:
>>> b = Bounds()
>>> b.method()
I am a bound method
>>> Bounds.method()
I am an unbound method free of the class instance!
All I get, however, is the last defined method within the class for both versions.
Any help would be appreciated - Thanks!
EDIT
For those interested in both bound and unbound usage (despite its obfuscating the API), it can be achieved with a few dirty hacks using a base class and lambda's in the constructor of the derived class:
class _Bounds(object):
def method(self, msg="Can you free me?"):
print('I am a bound method: "{}"'.format(msg))
class Bounds(_Bounds):
@staticmethod
def method():
print('I'm free from the shackles of the class instance!')
def __init__(self):
self.method = lambda **kw: _Bounds(self, **kw)
# do stuff
Then test with:
>>> Bounds().method()
I am a bound method: Can you free me?
>>> Bounds.method()
I'm free from the shackles of the class instance!