Class return statement not printing any output

前端 未结 1 1291
暗喜
暗喜 2021-01-21 11:35

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 d

1条回答
  •  心在旅途
    2021-01-21 11:51

    To answer your question - return does not print anything, but it is slightly confusing, since the interactive python prompt does print out the value of the last statement e.g.:

    Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
    [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 1+1
    2
    

    But if you create a file with contents 1+1 and 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.

    class className:
        def createName(self, name):
            self.name = name
        def displayName(self):
            return self.name
        def saying(self):
            print("Hello %s" % self.name)
    

    className has redundancy, you should rename your class just Name - also new style classes should always inherit object, so let's change your definition a bit:

    class Name(object):
        def createName(self, name):
            self.name = name
        def displayName(self):
            return self.name
        def saying(self):
            print("Hello %s" % self.name)
    

    Creating something is done automatically by overriding the classes __init__() method. e.g:

    class Name(object):
        def __init__(self, name):
            self.name = name
        def displayName(self):
            return self.name
        def saying(self):
            print("Hello %s" % self.name)
    

    this way you can already initialize your name when instantiating your class, e.g.

    first = Name("Jack")
    

    Second, display is handled idiomatically by overriding the method __repr__ e.g.

    class Name(object):
        def __init__(self, name):
            self.name = name
        def __repr__(self):
           return self.name
        def saying(self):
            print("Hello %s" % self.name)
    

    This way, you only need to do two things:

    >>> n = Name("Jack")
    >>> print n
    Jack
    

    0 讨论(0)
提交回复
热议问题