6

For dictionary we can use .get method. What about a class's attribute and provide a default value?

2 Answers 2

16

You can use hasattr and getattr.

For example:

hasattr(foo, 'bar')

would return True if foo has an attribute named bar, otherwise False and

getattr(foo, 'bar', 'quux')

would return foo.bar if it exists, otherwise defaults to quux.

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

1 Comment

+1. You might want to mention EAFP and try: / except AttributeError:
4

It's dead simple: use a keyword argument.

>>> class Foo(object):
...     def __init__(self, my_foo=None):
...         self.my_foo = my_foo
... 
>>> f = Foo()
>>> f.my_foo
>>> repr(f.my_foo)
'None'
>>> f2 = Foo(2)
>>> f2.my_foo
2

If you are looking for an object which does not have an attribute until you set it, Jason's idea is pretty good unless you directly refer to the attribute. You'll have to work around the AttributeError you'll get. Personally, I'm not a fan of creating objects which must be constantly surrounded by try/except blocks just for the sake of not setting an instance attribute.

Python isn't much for getters and setters. However, you can use property() to work around this problem:

>>> class Foo(object):
...     def __init__(self):
...         pass
...     def get_my_foo(self):
...         return getattr(self, "_my_foo", "there's no my_foo")
...     def set_my_foo(self, foo):
...         self._my_foo = foo
...     my_foo = property(get_my_foo, set_my_foo)
... 
>>> f = Foo()
>>> f.my_foo
"there's no my_foo"
>>> f.my_foo = "foo!"
>>> f.my_foo
'foo!'

It works just as well to call get_my_foo and set_my_foo, if you like. An added benefit is that you can omit the setter to make a read-only attribute, provided someone using your object doesn't change the underlying _my_foo.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.