Python Forum

Full Version: problem with print command in super()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
in the below code:
'''
Python Multiple Inheritance and MRO
super usage() in python
from: https://www.geeksforgeeks.org/python-super/
'''
class A:
	def age(self):
		print("Age is 21")
class B:
	def age(self):
		print("Age is 23")
class C(A, B):
	def age(self):
		super(C, self).age()
	
c = C()
print(f"result of c.age()is {c.age()}")
when the print line is inactive, nothing is displayed. when the print line is active, the output will be(I use Idle):
Output:
Age is 21 result of c.age()is None
I expect the output will be: result of c.age is Age is 21
why the Age is 21 is displayed before the print result? and what is the None in the result of print? namely, is c.age=None?
thanks
Method age() should not print anything, it should return a number! In your code, it returns None.
hi
no explanation to the above question?

if I want to have in output: age is 23, namely in class C,replace of A, B is called, how can be changed line 14?
I thought the explanation was clear. age() in all the classes needs to return a number. Currently it returns None. age() should not do a print.
class A:
    def age(self):
       return 21
class B:
    def age(self):
       return 23
class C(A, B):
    def age(self):
        return super(C, self).age()
     
c = C()
print(f"result of c.age()is {c.age()}")
But you really shouldn't specify the class for super. You should set up the class inheritance such that the MRO calls the correct superclass method. The only time you should use super(class, self) is when you need to go against the MRO.
class A:
    def age(self):
        return 21


class B:
    def age(self):
        return 23


class C(A, B):
    def age(self):
        return super().age()


c = C()
print(f"result of c.age()is {c.age()}")
I know this is just example code meant to demonstrate multiple inheritance and I shouldn't read much into the design, but it is a silly example and makes me question the quality of information you are getting from the link you reference.
hi, thanks for reply
in your code, without changing line 11 (class C(A, B)), how can I change line 13 ( return super().age() ) so that 23 is printed in output?
You should change line 11, but you could call B.age(self) in line 13