I’m writing an application with two basic class types:
- DocumentObject
- Property (of document object).
Property
instances are attributes of the DocumentObject
class and The Property
class has several simple attributes of its own (value, unit, etc.) and some methods.
In trying to make the scripting as user friendly as possible, I would like
objectName.propertyName
to return the value attribute of the Property instance, not the Property instance itself. Of course, it is possible to write objectName.propertyName.value
but most of the time, the user will be interacting with the value, not the Property instance.
It seems it should be possible to implement this behaviour using modified __getattr__
and __setattr__
methods in DocumentObject
like in the following example:
Input
class Property():
def __init__(self, name, value):
self.name = name
self.value = value
class DocumentObject():
def __init__(self, properties):
object.__setattr__(self, 'properties', dict())
self.properties = properties
def __getattr__(self, name):
if "properties" in vars(self):
if name in self.properties:
return self.properties(name).value
else: raise AttributeError
else: raise AttributeError
def __setattr__(self, key, value):
if key in self.properties:
self.properties(key).value = value
else:
object.__setattr__(self, key, value)
brick = DocumentObject({'length': Property('length',10), 'width': Property('width',5)})
print(brick.properties("length").name)
print(brick.length)
Output
length
10
Questions:
- Is is good practice to do this?
- Are there likely to be some negative consequences of this decision?
- Is there a more elegant solution that I have missed?