Abdul Khan
Abdul Khan

Reputation: 67

Why am i getting 'none' printed out in this piece of python3 code?

   class Parent:
       def __init__(self,a):
           self.a = a
       def method1(self):
           print(self.a*2)
       def method2(self):
           print(self.a+'!!!')

   class Child(Parent):
       def __init__(self, a, b):
           self.a =a
           self.b =b
       def method1(self):
           print(self.a*7)
       def method3(self):
           print(self.a + self.b)


p= Parent('hi')
c= Child('hi', 'bye')

print('Parent method 1:', p.method1())
print('Parent method 2:', p.method2())
print()
print('Child method 1:', c.method1())
print('Child method 2:', c.method2())
print('Child method 3:', c.method3())

When it runs I get this as the output: hihi Parent method 1: None hi!!! Parent method 2: None

    hihihihihihihi
    Child method 1: None
    hi!!!
    Child method 2: None
    hibye
    Child method 3: None

Why do i get 'None' printed when instead the responses should be printed besides the print statements ?

Upvotes: 0

Views: 87

Answers (1)

ghost
ghost

Reputation: 1207

print('Parent method 1:', p.method1()) will print the return value of method1(). Since method1 is a print function, and does not return a value, it prints None.

I guess what you're trying to do should be achievable by:

def method1(self):
    return self.a*2

Edit: The code was run on Python3.7. The result obtained is attached. enter image description here

Upvotes: 2

Related Questions