Python: Adding Fields to Objects Dynamically

主宰稳场 提交于 2020-01-03 07:25: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:

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?


回答1:


Try this:

class Object:
    pass

obj = Object()
obj.x = 5



回答2:


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



来源:https://stackoverflow.com/questions/4443301/python-adding-fields-to-objects-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!