Moving from PHP to Python. Part Two
Jon Clements
joncle at googlemail.com
Mon Dec 14 14:49:40 EST 2009
>
> class Registry:
>
> data = {}
>
> def __init__(self,environ):
> self.data['env'] = environ
> self.data['init'] = 'hede'
>
> def set_entry(self,key,data):
> self.data[key] = data
>
> def get_entry(self,key):
> return self.data[key]
>
> def debug(self):
>
> r = '<pre>'
> r += repr(self.data)
> r += '</pre>'
>
> return r
>
Just thought of something else:
set_entry and get_entry are probably (in your example) better written
as:
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, val):
self.data[key] = val
Assuming the syntax makes sense for the object.
Then just use object[4] = 'adsfasfd' and object[4] syntax...
Or as a getter/setter as per http://docs.python.org/library/functions.html#property
Or depending on the use case for your class, just inherit from the
built-in dict and get its functionality.
>>> class Test(dict):
def debug(self, whatever):
print whatever
>>> x = Test()
>>> x[3] ='adfadsf'
>>> x[3]
'adfadsf'
>>> x.debug('test')
test
hth
Jon.
More information about the Python-list
mailing list