【问题标题】:There is a problem when calling another function from a function in the same class从同一个类中的函数调用另一个函数时出现问题
【发布时间】:2021-04-15 00:01:21
【问题描述】:

我使用python3。 从类中的函数调用另一个函数时无法识别。 这是我的代码和错误消息

这些代码删除了所有复杂的东西,只删除了重要的东西。我只想在主函数中调用 get_contents() 。 get_contents() 应该调用 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

帮帮我。请

""" 我正在通过查看文档来学习 Python。我不知道主要功能必须在功能之外。 感谢所有提供帮助的人,即使这太容易了。 """

【问题讨论】:

  • 你想用if __name__ == "__main__": contents = get_contents() print (contents)做什么。预期的输出是什么?
  • 这些代码删除了所有复杂的东西,只有那些重要的东西。我只想在主函数中调用 get_contents() 。 get_contents() 应该调用 get_response()。
  • 你试图调用类方法而不实例化?
  • 感谢您的帮助和关注。多亏了这一点,结果很好。

标签: python python-3.x methods call


【解决方案1】:
  1. main 应该不在类中。
  2. 类内部的动作可能接收 self 作为参数; get_response 可以在没有它的情况下处理,并且可以是静态的,如果是这样,那么 get_contents 可能也应该是静态的。如果是这样,你应该在它之前添加一个装饰器:@staticmethod

我猜你的代码应该是:

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)

【讨论】:

  • 多亏了你,我轻松解决了。我很笨拙,因为我是 python 新手。希望以后能多多帮助。
【解决方案2】:

我不知道你想要达到什么目的。但这是我的类似方法。 如果要使方法成为静态方法,则可以避免实例化。

class TClass:
    @staticmethod
    def get_response():
        return 'response'
    
    @staticmethod
    def get_contents():
        content = TClass.get_response()
        return content

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

【讨论】:

  • 谢谢。但我不想要一个静态方法。我只是不知道main函数必须在函数之外。
猜你喜欢
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
相关资源
最近更新 更多