Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Adding Fields to Objects Dynamically

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?

like image 518
Rafid Avatar asked Dec 14 '10 19:12

Rafid


2 Answers

Try this:

class Object:
    pass

obj = Object()
obj.x = 5
like image 82
gruszczy Avatar answered Sep 29 '22 21:09

gruszczy


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

like image 44
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 21:10

Ignacio Vazquez-Abrams