简体   繁体   English

如何使用 Python 在运行时创建属性?

[英]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:到目前为止我的想法:

  1. Create a subclass of property that includes metadata required for extracting the extra information from the interface创建一个属性的子类,其中包含从接口中提取额外信息所需的元数据
  2. Refactor the existing data objects to use the new property subclass for relevant fields in the UI重构现有数据对象以使用 UI 中相关字段的新属性子类
  3. Create a new generator class that accepts the UI driver object and the data object that创建一个新的生成器 class 接受 UI 驱动程序 object 和数据 object
    • reflects the data object to get a list of all the members of it that are of the new property subclass type反映数据 object 以获取其中属于新属性子类类型的所有成员的列表
    • stores the information from the UI based upon the metadata in the property subclass to members of the generator class instance (planning on using setattr )根据属性子类中的元数据将来自 UI 的信息存储到生成器 class 实例的成员(计划使用setattr
    • create properties at run time to make the members created in (b) read-only and provide an interface consistent with existing code (ie using .[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.但是您可以使用getattrsetattr方法定义动态只读属性。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM