Python: instance attribute error

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'

+5
source share
3 answers
class Person:

    def __init__(self,person_dict):
        self.name = person_dict.get('name')

self.name = person_dict.get('name') Exception, Person name (None )

UPD. - getName , . name attr .

+6
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
+3

, , name. , , - name = None ( , ) . "" .

class Person:
    name = None
    def __init__(self,person_dict):
        try:
            self.name = person_dict['name']
        except Exception:
            pass

__init__ :

def __init__(self,person_dict):
    self.name = person_dict.get('name')

get() None, , .

0

All Articles