Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: instance attribute error

Tags:

python

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'

like image 909
remy Avatar asked Apr 18 '12 13:04

remy


2 Answers

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.

like image 79
San4ez Avatar answered Oct 09 '22 15:10

San4ez


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
like image 27
vartec Avatar answered Oct 09 '22 14:10

vartec