I have a number of Python types that describe a hierarchy in the sense that they are increasingly specific in terms of their properties. Instead of trying to describe it in words, here is an example:
class A:
@property
def prop1(self):
return self._prop1
class B:
@property
def prop1(self):
return self._prop1
@property
def prop2(self):
return self._prop2
class C:
@property
def prop1(self):
return self._prop1
@property
def prop2(self):
return self._prop2
@property
def prop3(self):
return self._prop3
So, as you go down the class list, B has all of the properties of A and then some extra ones. C has all of the properties of B and then some extra ones, and so on. I would like to minimize the duplication of the above definitions if possible.
One obvious solution would be to use inheritance, making B a subclass of A and so on. However, the semantics of these types do not follow an is-a relationship; I do not want isinstance(bObject, A) to be True. Is there an alternative way in Python to straightforwardly allow this sharing of attributes without using subclasses?
You can use a decorator:
def has_prop1(cls):
@property
def prop1(self):
return self._prop1
cls.prop1 = prop1
return cls
@has_prop1
class A(object):
pass
Compositing would go like this:
@has_prop1
@has_prop2
class B(object):
pass
Or even like this:
def has_many_properties(cls):
return has_prop1(has_prop2(has_prop3(cls)))
@has_many_properties
class C(object):
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With