[Tutor] Why is this printing None?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 15 19:15:02 EDT 2020


On 15/04/2020 14:24, Cranky Frankie 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())


Others have answered your original question.

It is worth pointing out that putting a print() inside
a class like this is usually the wrong thing to do.
It is better if the class returns a string which can
be printed by the caller. This is known as separation
of presentation and logic.

And it is better still, in this case, if the function
returning the string is called __str__(). That then
means the object can be printed directly:

class Employee:

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

     def __str__(self):
         return "Name : " + self.name
if __name__ == '__main__':
     emp1 = Employee('Zara')
     print(emp1)

Notice we print the object (no need to call any methods)
and print internally calls the obj.__str__() method to
get the string.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list