I tried this inheritance code and got an unexpected output. Kindly guide me where is my fault.
Child.py
from ParentClass import Parent
class ChildImp(Parent):
var2 = 200
def __init__(self):
Parent.__init__(self, 8, 3)
def getData(self):
self.var1 self.Sub() self.Add()
obj = ChildImp()
print(obj.getData())
ParentClass.py
class Parent:
var1 = 100
def __init__(self, a, b):
self.firstNUm = a
self.secondNUm = b
def Add(self):
return self.firstNUm self.secondNUm
def Sub(self):
return self.firstNUm - self.secondNUm
obj1 = Parent(4, 6)
print(obj1.Add())
obj2 = Parent(9, 2)
print(obj2.Sub())
output:
10
7
None
Process finished with exit code 0
Where does this 10 and 7 come from? Why there is a None in the output?
CodePudding user response:
The output is from each of the following calls
10 # print(obj1.Add())
7 # print(obj2.Sub())
None # print(obj.getData())
note that Add
and Sub
will return
the computed value, btu getData
has no return
so will implicitly return None
hence the last output.
Note that the reason those Add
and Sub
lines are executing is because of the import
statement. If you only want those to run when that script is directly invoked you would modify that block to
if __name__ == '__main__':
obj1 = Parent(4, 6)
print(obj1.Add())
obj2 = Parent(9, 2)
print(obj2.Sub())
CodePudding user response:
Output is from the 3 print statements.
print(obj1.Add()) # prints 10
print(obj2.Sub()) # prints 7
print(obj.getData()) # prints None
Need a return on ChildImp getData() function otherwise returns None.
from ParentClass import Parent
class ChildImp(Parent):
var2 = 200
def __init__(self):
Parent.__init__(self, 8, 3)
def getData(self):
return self.var1 self.Sub() self.Add() # <== added return
obj = ChildImp()
print(obj.getData())
Also good practice to add if name == __main__
check in the parent class so only the main in the class called is executed.
# ParentClass.py
class Parent:
...
if __name__ == '__main__':
obj1 = Parent(4, 6)
print(obj1.Add())
obj2 = Parent(9, 2)
print(obj2.Sub())
CodePudding user response:
10 and 7 are the return values of the Add
and Sub
methods
The None is there because getData
does not return anything
For all three values there is a print
call.