0

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!
3
  • 1
    You'd have to use a special descriptor object to handle the two contexts differently. I duped you to a question where I used the same technique to bind to either the class or the instance. Commented Mar 16, 2015 at 14:14
  • 2
    I would, however, strongly advice you to rethink your API and avoid such confusing overloading of meaning. Commented Mar 16, 2015 at 14:15
  • Perfect - thanks for the swift answer Martijn. Whilst I agree that it is not necessarily best practice, I was simply wondering if you could do both as a matter of academic interest. Once again the powers of Python never cease to amaze me... Commented Mar 17, 2015 at 7:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.