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:
['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']