Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine properties defined by different parent classes in python?

Suppose we have two classes and each computes a property stuff in a different way. Is is possible to combine their outputs in a method/property of a child class?

The following code shows the desired effect (though get_stuff_from needs to be replaced by a proper python construct, if such thing exists).

class Foo():
    @property
    def stuff(self):
        return ['a','b','c']

class Bar():
    @property
    def stuff(self):
        return ['1','2','3']

class FooBar(Foo, Bar):
    @property
    def stuff(self):

        # Computes stuff from the internal state like Foo().stuff
        foo_stuff = get_stuff_from(Foo)

        # Computes stuff from the internal state like Bar().stuff
        bar_stuff = get_stuff_from(Bar)

        # Returns the combined results
        return foo_stuff + bar_stuff

foo_bar = FooBar()
print(foo_bar.stuff)

which should output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['a', 'b', 'c', '1', '2', '3']

If stuff were a method instead of a property, this would be simple to implement:

class Foo():
    def stuff(self):
        return ['a','b','c']

class Bar():
    def stuff(self):
        return ['1','2','3']

class FooBar(Foo, Bar):
    def stuff(self):

        # Computes stuff from the internal state like Foo().stuff
        foo_stuff = Foo.stuff(self)

        # Computes stuff from the internal state like Bar().stuff
        bar_stuff = Bar.stuff(self)

        # Returns the combined results
        return foo_stuff + bar_stuff

foo_bar = FooBar()
print(foo_bar.stuff())

however, I would like to find out whether it is possible to do the same with properties.

>Solution :

A property is just an object with an fget method. You could access the base class’ property object and invoke its fget method with the self object that refers to the child class:

class FooBar(Foo, Bar):
    @property
    def stuff(self):

        # Computes stuff from the internal state like Foo().stuff
        foo_stuff = Foo.stuff.fget(self)

        # Computes stuff from the internal state like Bar().stuff
        bar_stuff = Bar.stuff.fget(self)

        # Returns the combined results
        return foo_stuff + bar_stuff

And now FooBar().stuff returns ['a', 'b', 'c', '1', '2', '3']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading