Python Forum
problem with print command in super() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: problem with print command in super() (/thread-41514.html)



problem with print command in super() - akbarza - Jan-29-2024

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


RE: problem with print command in super() - Gribouillis - Jan-29-2024

Method age() should not print anything, it should return a number! In your code, it returns None.


RE: problem with print command in super() - akbarza - Jan-30-2024

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?


RE: problem with print command in super() - deanhystad - Jan-30-2024

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.


RE: problem with print command in super() - akbarza - Feb-01-2024

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?


RE: problem with print command in super() - deanhystad - Feb-01-2024

You should change line 11, but you could call B.age(self) in line 13