user22605
0
Q:

python multiple inheritance diamond problem

# example of diamond problem and multiple inheritance

class Value():                                                               
    def __init__(self, value):
        self.value = value
        print("value")

    def get_value(self):
        return self.value
        
class Measure(Value):                                                               
    def __init__(self, unit, *args, **kwargs):
        print ("measure")
        self.unit = unit
        super().__init__(*args, **kwargs)
        
    def get_value(self):
        value = super().get_value()
        return f"{value} {self.unit}"

class Integer(Value):
    def __init__(self, *args, **kwargs):
        print("integer")
        super().__init__(*args, **kwargs)
        
    def get_value(self):
        value = super().get_value()
        return int(value)

class MeasuredInteger(Measure, Integer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        
mt = MetricInteger("km", 7.3)
# prints:
# measure
# integer
# value

mt.get_value() # returns "7 km"
0
# Example of multiple inheritance
# I recommend to avoid it, because it's too complex to be relyed on.

class Thing(object):
    def func(self):
        print("Function ran from class Thing()")

class OtherThing(object):
    def otherfunc(self):
        print("Function ran from class OtherThing()")
      
class NewThing(Thing, OtherThing):
    pass

some_object = NewThing()

some_object.func()
some_object.otherfunc()
-1

New to Communities?

Join the community