【问题标题】:Calling a function from from a function within a class从类中的函数调用函数
【发布时间】:2016-03-24 02:49:07
【问题描述】:

我是面向对象编程的新手,对以下问题有疑问。

class TestClass():
    def test(arg1,arg2):
        global message
        print(arg1,arg2)
        message=str(arg1)+' '+str(arg2)
        print message

    def test0( self, twoword ):       
        global word1,word2
        word1=twoword.split('-')[0]
        word2=twoword.split('-')[1]
        print(word1,word2)
        TestClass.test(word1,word2)

程序的功能是多余的,可以简化,但我希望从 test() 调用 test()。怎么办? 谢谢。

【问题讨论】:

  • 这不能回答您的问题,但是您忘记了 test()self 参数。此外,没有理由使用global

标签: python function class oop


【解决方案1】:

您需要将test 设为静态方法(可以在没有类实例的情况下调用的方法)。你可以用staticmethod装饰器来做。

class TestClass():
    @staticmethod  # <---
    def test(arg1, arg2):
        global message
        print(arg1,arg2)
        message=str(arg1)+' '+str(arg2)
        print message

    def test0(self, twoword):
        global word1,word2
        word1=twoword.split('-')[0]
        word2=twoword.split('-')[1]
        print(word1,word2)
        TestClass.test(word1,word2)

【讨论】:

    【解决方案2】:

    如果您正在寻找函数重载 Python function overloading

    如果你只是想让这段代码工作,那么在测试上方添加一个@staticmethod。

    class TestClass():
       @staticmethod
       def test(arg1,arg2):
           global message
           print(arg1,arg2)
           message=str(arg1)+' '+str(arg2)
           print message
    
       def test0( self, twoword ):
           word1=twoword.split('-')[0]
           word2=twoword.split('-')[0]
           global word1,word2
           print(word1,word2)
           TestClass.test(word1,word2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 2011-12-07
      • 2021-05-18
      • 1970-01-01
      相关资源
      最近更新 更多