5

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'

1
  • As you've already seen in the answers, getters are not 'pythonic', or good python code. Here's a great article on why this is. To sum the article up: Java always needs getters/setters because without them, refactoring to use them is difficult. With python, you don't change your interface, as you can use properties. Commented Apr 18, 2012 at 15:01

3 Answers 3

6
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.

Sign up to request clarification or add additional context in comments.

4 Comments

It's worth noting that 'getter' methods are bad practice in Python - access it directly.
I know, I'm just saying an answer that notes that is a better one.
so the better way in python is access attribute directly?
@remy Yes. The reason to use getters and setters in Java is to leave the class unchanged to code using it if you need to add operations. In Python, we have the property() builtin, so there is no need to do this.
3
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

Comments

0

If you don't want the exception, then you should make sure the instance has a value for name. Since lookup falls back to the class if an attribute can't be found on the instance, an easy way to do this is to simply add name = None (or whatever default value you want the instance to use) to the class definition. Assignment to the attribute on the instance will "hide" the default value.

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

You could instead write your __init__ like this:

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

The get() method of dictionaries returns None if the key isn't found, or you can provide a second argument with a different default value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.