python - Is it more pythonic to manipulate object I/O with @property vs override __getitem__? -
given dictionary of data (could come database entry), more correct way wrap dictionary's data in encapsulating class has control on data can set , returned as?
specifically, 2 ways have in mind to:
- override
dict
inherited class'__getitem__
,__setitem__
methods - within standard
object
inherited class, add@property
decorator each data entry needs controlled.
for example:
class smartcontainer(dict): ## format/check items returned def __getitem__(self,key): if key == "birthday": return "happy birthday!{bdate}".format(bdate=self.get('birthday')) if key not in self.keys(): return 0 def __init__(self,basedict): super(smartcontainer,self).__init__(basedict) class smartcontainer2(object): @property def birthday(self): return "happy birthday! {bdate}".format(bdate=self._birthday) @birthday.setter def birthday(self,value): self._birthday = value def __init__(self, basedict): [self.__setattr__(k,v) k,v in basedict.iteritems()]
in purely arbitrary example, have 2 classes implement each architecture.
smartcontainer=smartcontainer({"pi":3.14, "birthday":"01/01/2016"}) smartcontainer['birthday'] >>>'happy birthday! 01/01/2016' smartcontainer2=smartcontainer2({"pi":3.14, "birthday":"01/01/2016"}) smartcontainer2.birthday >>>'happy birthday! 01/01/2016'
both methods work, , seems me @property
decorator more used such actions. dynamic nature of smartcontainer
class' access abilities seem more straightforward me. aka smartcontainer[dynamic_key]
vs smartcontainer2.__getattr__(dynamic_key)
.
i wondering if there reason use 1 method on other, , potential pitfalls exist?
Comments
Post a Comment