I get a dict to initialize a class person. There is one field: "name". The name field is optional, which means that if the dict does not have a name element, then there is no name for the person. I use getter methods to get the instance attribute, but it will throw an error if there is no "name" value. I don’t know if there is a good programming style to improve my code? Since python creates an instance field at runtime, I don't know how to use getter as 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 does not have the attribute 'name'
source
share