None is displayed on the method call of the Python parent class.

Asked 2 years ago, Updated 2 years ago, 16 views

class Animal:
    def __init__(self, name):
        self.name = name

    def get_name(self):
        print("name:", self.name)

    def speak(self):
        pass


class Dog(Animal):
    def speak(self):
        print("bark")


dog = Dog("doggy")
print(dog.get_name())

If you print out the above code, the results are as follows.

name: doggy
None

The get_name() method of the parent class Animal itself seems to be invoked normally...

Where did none come from?

python

2022-09-22 10:16

2 Answers

self.The output of name is performed at get_name and the return value is not specified, so the return value is None.
When you output this value again, None is output.


2022-09-22 10:16

Think about it carefully.

print("name:", self.name) print out

print(dog.get_name()) This syntax outputs the result of the get_name method.

But...The get_name method has a result of None.

In [5]: print(None)
None

In [6]: a = dog.get_name()
name: doggy

In [7]: print(a)
None


2022-09-22 10:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.