I’m learning about Classes and am having a problem with the return statement (is it a statement? I hope so), the program prints out nothing, it just ends without doing anything.
class className:
def createName(self, name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print("Hello %s" % self.name)
first = className()
second = className()
first.createName("Jack")
second.createName("Joy")
first.displayName()
second.displayName()
I know I’m doing something so obviously wrong but I really don’t know what. I’d appreciate some help.
To answer your question –
returndoes not print anything, but it is slightly confusing, since the interactive python prompt does print out the value of the last statement e.g.:But if you create a file with contents
1+1and run it as a python script, nothing is printed.Since you say that you are a newbie, I’ll give you a few pointers on how to improve your code.
classNamehas redundancy, you should rename your class justName– also new style classes should always inheritobject, so let’s change your definition a bit:Creating something is done automatically by overriding the classes
__init__()method. e.g:this way you can already initialize your name when instantiating your class, e.g.
Second,
displayis handled idiomatically by overriding the method__repr__e.g.This way, you only need to do two things: