开发者

Python: Adding Fields to Objects Dynamically

开发者 https://www.devze.com 2023-01-31 03:10 出处:网络
I am wondering whether it is possible to add fields to objects dynamically. For example, I 开发者_运维问答want to be able to add something like:

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?


Try this:

class Object:
    pass

obj = Object()
obj.x = 5


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

0

精彩评论

暂无评论...
验证码 换一张
取 消