14

I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like:

user = object()
user.first_name = 'John'
user.last_name = 'Smith'

When I execute that in Python command line interpretor I get:

AttributeError: 'object' object has no attribute 'first_name'

Any idea?

2 Answers 2

21

Try this:

class Object:
    pass

obj = Object()
obj.x = 5
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that worked for me. I have two questions 1) What does the 'pass' keyword mean here? 2) If I have another instance obj2 of Object() in my code, will obj.x create obj2.x (with some undefined value)?
1) Regarding pass: docs.python.org/tutorial/controlflow.html#pass-statements 2) No, when you do obj.x = 5, you only add x attribute to single instance of Object. If you want all Object instances to share x, you have to do Object.x = 5.
There is no such thing as an undefined value in Python - the closest it gets is None. Objects created in the way gruszczy proposes do not have any kind of "prototype"; you can add and delete attributes at will, and it has no effect on any other instance of the Object class.
Nice simple way to fake up an object with an attribute, thanks!
7

You cannot assign to attributes of object instances like this. Derive from object, and use an instance of that class.

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.