开发者

How to create properties at runtime with Python?

开发者 https://www.devze.com 2023-03-16 18:33 出处:网络
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

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. 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
  3. Create a new generator class that accepts the UI driver object and the data object that
    • reflects the data object to get a list of all the members of it that are of the new property subclass type
    • 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)
    • 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]())

I think I have everything figured out except step 3c. Is there a way to create properties dynamically 开发者_JAVA技巧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. 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
0

精彩评论

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

关注公众号