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