Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

python - There is a problem when calling another function from a function in the same class

I use python3. It is not recognized when another function is called from a function in the class. here my code and error message

These codes erase all the complex stuff, and only the ones that matter. I just want to call get_contents() in the main function. And get_contents() should call get_response().

class TClass:
    def get_response():
        return 'response'

    def get_contents():
        content = get_response()
        return content

    if __name__   == "__main__":
        contents = get_contents()
        print (contents)
Traceback (most recent call last):
  File "/Users/mul/Project/mybase.py", line 2, in <module>
    class TClass:
  File "/Users/mul/Project/mybase.py", line 11, in TClass
    contents = get_contents()
  File "/Users/mul/Project/mybase.py", line 7, in get_contents
    content = get_response()
NameError: name 'get_response' is not defined

help me. please

""" I am studying Python by looking at the documents. I didn't know that the main function had to be outside the function. Thanks to everyone who helped, even though it was too easy. """

question from:https://stackoverflow.com/questions/65643230/there-is-a-problem-when-calling-another-function-from-a-function-in-the-same-cla

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. The main should be out of the class.
  2. The actions inside of the class probably receive self as a parameter; get_response could handle without it, and could be static, and if so then get_contents probably should be static too. If so, you should add a decorator before it: @staticmethod.

I guess that your code should be:

class TClass:
    def get_response(self):
        return 'response'

    def get_contents(self):
        content = self.get_response()
        return content

if __name__   == "__main__":
    object_t = TClass()
    contents = object_t.get_contents()
    print (contents)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...