Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share attributes without an is-a relationship in Python?

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?

like image 525
Jason R Avatar asked Dec 31 '25 01:12

Jason R


1 Answers

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
like image 134
orlp Avatar answered Jan 02 '26 15:01

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!