[Tutor] Why is this printing None?

David Rock david at graniteweb.com
Wed Apr 15 10:07:44 EDT 2020


> On Apr 15, 2020, at 08:24, Cranky Frankie <cranky.frankie at gmail.com> wrote:
> 
> I have this simple class in Python 3.8. When I run this in IDLE or at the
> command prompt the word None gets printed after the employee name. Why?
> 
> class Employee:
> 
>    def __init__ (self, name):
>        self.name = name
> 
>    def displayEmployee(self):
>        print("Name : ", self.name)
> 
> if __name__ == '__main__':
>    emp1 = Employee('Zara')
>    print(emp1.displayEmployee())


As others have pointed out, you aren’t printing what you think should be printed.
emp1.displayEmployee() prints the name, then you are printing the return value of displayEmployee()

If you change your code to this, it will do what you probably want, but this might not be the best way to do it (but fits the intentions of what your code implies).

if __name__ == '__main__’:
    emp1 = Employee('Zara’)
    emp1.displayEmployee()

Note that what I’m doing is allowing the Class method to handle the printing (your external print is redundant, and the reason for the “None”) as already noted.

If you want the external print statement, instead of having a displayEmployee() method, maybe use a __str__ method to dictate what printing the object means, or have a getter method that just returns self.name so it can be printed.

It all depends what your overall needs are.


— 
David Rock
david at graniteweb.com






More information about the Tutor mailing list