3

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 2

8

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

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

1 Comment

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

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.
@delan: fixed it as you suggested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.