Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we get an optional class attribute in Python?

Tags:

python

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

like image 254
User007 Avatar asked Aug 06 '13 17:08

User007


Video Answer


1 Answers

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.

like image 52
jason Avatar answered Nov 02 '22 22:11

jason