I get a dict to init a class person. there is one field in person: 'name'. 'name' field is optional, meaning that if the dict don't have the 'name' item, then there's no 'name' value of person. I use getter methods to get instance attribute, but it will throw a error if there's no 'name' value. I don't know is there any good programming style to improve my code? Because python create instance field at run time, I don't know how to use getter like java.
class Person:
def __init__(self,person_dict):
try:
self.name = person_dict['name']
except Exception:
pass
def getName(self):
return self.name
pdict = {}
p = Person(pdict)
print p.getName()
AttributeError: Person instance has no attribute 'name'
class Person:
def __init__(self,person_dict):
self.name = person_dict.get('name')
In this case self.name = person_dict.get('name')
won't raise Exception and Person objects will have name
attribute (None
by default)
UPD. Because of getName
method is useless, I cut it down from example. Access name
attr directly.
class Person:
def __init__(self,person_dict):
self.name = person_dict.get('name', 'default_name')
pdict = {}
p = Person(pdict)
print p.name # there is no need for getter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With