0

I'm a little confused about an inheritance problem in python.
I know the following example is "stupid" but I simplify my initial problem.
Imagine we have 3 classes

class testT(object):
    def check(self, str):
       return "t" in str

class testTE(testT):
    def check(self, str):
       return "e" in str

class testTES(testTE):
    def check(self, str):
       return "s" in str

And I would like an output like :

>>> print testTES().check("test")
>>> True    (Because string "test" contains "s","e" and "t" characters)
>>> print testTES().check("dog")
>>> False
>>> print testTES().check("dogs")
>>> False   (Contains a "s" but no "e" and no "t")
>>> print testTE().check("tuple")
>>> True    (Contains "e" and "t")

How can I implement this behavior ? I tried with 'super' but my method wasn't successfull.
Thanks for your help

1
  • 1
    Just as a comment, note that this is not what is known as multiple inheritance. Here every class has a single parent so it is single inheritance (even if the inheritance hierarchy has more than one level). Multiple inheritance occurs when a class has more than one parent at the same time, leading to issues like the "diamond problem" and confusing priority rules in the case two inherited methods have the same signature (or just the same name, in Python). Commented Nov 27, 2018 at 15:51

1 Answer 1

4

You just need to combine the check calls in the subclasses with the output of super(...).check():

class testT(object):
    def check(self, str):
        return "t" in str

class testTE(testT):
    def check(self, str):
        return super(testTE, self).check(str) and "e" in str

class testTES(testTE):
    def check(self, str):
        return super(testTES, self).check(str) and "s" in str

print(testTES().check("test"))
# True
print(testTES().check("dog"))
# False
print(testTES().check("dogs"))
# False
print(testTE().check("tuple"))
# True
Sign up to request clarification or add additional context in comments.

2 Comments

Note OP appears to be using Python 2, so super and print would be slightly different in that case.
@jdehesa I fixed the calls to super, in this case print(...) works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.