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)?
>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)