Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How can I call the original of an overloaded method?

Let’s say I have this:

class MyPackage ( dict ) :
  def __init__ ( self ) :
    super().__init__()

  def __setitem__ ( self, key, value ) :
    raise NotImplementedError( "use set()" )

  def __getitem__ ( self, key ) :
    raise NotImplementedError( "use get()" )

  def set ( self, key, value ) :
    # some magic
    self[key] = value

  def get ( self, key ) :
    # some magic
    if not key in self.keys() : return "no!"
    return self[key]

(Here, # some magic is additional code that justifies MyPackage as opposed to ‘just a dictionary.’)

The whole point is, I want to provided a dictionary-like object that forces the use of get() and set() methods and disallows all access via [], i.e. it is not permitted to use a['x']="wow" or print( a['x'] ) However, the minute I call get() or set(), the NotImplementedError is raised. Contrast this with, say, Lua, where you can bypass "overloading" by using "raw" getters and setters. Is there any way I can do this in Python without making MyPackage contain a dictionary (as opposed to being a dictionary)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You already have the solution in your code: use super(). This allows you to call methods on the parent class, in this case, dict:

  def set ( self, key, value ) :
    # some magic
    super().__setitem__(key, value)

  def get ( self, key ) :
    # some magic
    if not key in self.keys() : return "no!"
    return super().__getitem__(key)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading