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. My idea so far:
- Create a subclass of property that includes metadata required for extracting the extra information from the interface
- Refactor the existing data objects to use the new property subclass for relevant fields in the UI
- 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
精彩评论