如何在Python中创建新的未知或动态/扩展对象 [英] How to create a new unknown or dynamic/expando object in Python
问题描述
在python中,我们如何在没有预定义类的情况下创建新对象,然后动态地向其添加属性?
In python how can we create a new object without having a predefined Class and later dynamically add properties to it ?
示例:
dynamic_object = Dynamic()
dynamic_object.dynamic_property_a = "abc"
dynamic_object.dynamic_property_b = "abcdefg"
最好的方法是什么?
编辑,因为很多人在评论中建议我可能不需要它.
EDIT Because many people advised in comments that I might not need this.
问题是我有一个序列化对象属性的函数.因此,由于某些构造函数的限制,我不想创建预期类的对象,而是创建一个类似的对象,比如说 mock ,添加任何自定义"属性需要,然后将其反馈给函数.
The thing is that I have a function that serializes an object's properties. For that reason, I don't want to create an object of the expected class due to some constructor restrictions, but instead create a similar one, let's say like a mock, add any "custom" properties I need, then feed it back to the function.
推荐答案
只需定义自己的类即可:
Just define your own class to do it:
class Expando(object):
pass
ex = Expando()
ex.foo = 17
ex.bar = "Hello"
这篇关于如何在Python中创建新的未知或动态/扩展对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!