For example, the object only have two attributes, person object, in this example, only have first name, and second name. Is this possible to make a gender attribute on the fly? Thanks.
2 Answers
short answer: yes
class Person(object):
def __init__(self):
self.first_name = 'Will'
self.second_name = 'Awesome'
my_guy = Person()
my_guy.gender = "Male"
print(my_guy.gender)
will print Male
1 Comment
Daenyth
Care should be taken with this approach: If you call
Person().gender, you'd get an AttributeError, so make sure to catch it if it's possible the attr isn't there.In case you even know what this attribute is called when you write code, you can
my_guy = Person()
attr = 'secret_habit' # this could be read from file, keybrd etc.
value = 'wont tell you'
setattr( my_guy, attr, value)
print(my_guy.secret_habit)
i get 'wont tell you'
2 Comments
Forget about
__dict__ and use setattr/getattr. Accessing the instance dictionary is fragil, it fails in a number of cases (e.g. __slots__, old-style classes, properties, other attribute access overriding, possibly even more) that may not be the majority, but definitely common enough to consider.yosukesabai
@delan: fixed it as you suggested.