[英]How to create properties at runtime with Python?
So I'm trying to figure out if what I want to do is even possible.所以我试图弄清楚我想做的事情是否可能。 I am writing some test code for an application, and I have objects that contain properties representing some of the elements we have in the interface for our product.我正在为应用程序编写一些测试代码,并且我的对象包含代表我们产品界面中的一些元素的属性。 What I want to do is be able to pass in the application runner and the data object to a new class and have it dynamically generate a set of accessor properties based upon a subset of the properties in the data object.我想要做的是能够将应用程序运行器和数据 object 传递给新的 class 并让它根据数据 ZA8CFDE6331BD59EB2AC96F8911C4B66 中的属性子集动态生成一组访问器属性My idea so far:到目前为止我的想法:
setattr
)根据属性子类中的元数据将来自 UI 的信息存储到生成器 class 实例的成员(计划使用setattr
).[name]
instead of .[name]()
)在运行时创建属性以使 (b) 中创建的成员只读并提供与现有代码一致的接口(即使用.[name]
而不是.[name]()
)I think I have everything figured out except step 3c.我想除了步骤 3c 之外,我已经弄清楚了一切。 Is there a way to create properties dynamically at runtime?有没有办法在运行时动态创建属性? Any help would be greatly appreciated.任何帮助将不胜感激。
Not sure that's what you want.不确定那是你想要的。 But you could define dynamic read-only property with getattr and setattr method.但是您可以使用getattr和setattr方法定义动态只读属性。 Here is an example:这是一个例子:
class X(object):
data = {'x' : 123, 'y' : 456}
def __getattr__(self, name):
if name in self.data:
return self.data[name]
raise AttributeError(name)
def __setattr__(self, name, value):
if name in self.data:
return None
return super(X, self).__setattr__(name, value)
a = X()
print a.x, a.y
a.x = 0
print a.x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.