在其他函数中调用先前定义的函数(Python)

时间:2014-10-14 20:01:58

标签: python function object

我知道这个问题已经在这个网站上被问了很多,但出于某种原因无论我看到什么并尝试它都没有帮助我的代码。我正在为一个小型游戏开发越来越广泛的战斗算法,并且在定义所有数学函数的对象中,我还想要一个具有一堆打印语句的函数,这些函数可以在这些其他函数中调用,所以我在每个函数中都没有相同的打印语句。 因此,简化版本将是:

def print():
     print("stuff and things")
def combatMath():
     #math stuff happens here
     print()
     #call print to print out the results

print函数将接受来自对象的参数,以及combatMath的结果然后打印出来,以便您可以看到当前的HP,EP,MP等。 所以,基本上这归结为能够在另一个函数中调用一个函数,我似乎无法弄清楚。一个简单的解释将不胜感激。如果我需要详细说明,请告诉我。

1 个答案:

答案 0 :(得分:0)

您正在调用内置print而不是您为您的班级定义的内容。使用self.print()

调用该名称
class test:
    def print(self):
         print("stuff and things")
    def combatMath(self):
         #math stuff happens here
         self.print()
         #call print to print out the results

[编辑]

即使你不使用内置内容,Python仍然不知道在哪里看。告诉它查看该方法的类声明会将其指向您想要的位置:

class test:
def t1(self):
     print("stuff and things")
def t2(self):
     #math stuff happens here
     self.t1()
     #call print to print out the results

用这个

运行
c = test()
c.t2()

给出了预期的

"stuff and things"

而不是这个声明,它不知道在哪里找到t1因此给出了

NameError: global name 't1' is not defined

class test:
    def t1(self):
         print("stuff and things")
    def t2(self):
         #math stuff happens here
         t1()
         #call print to print out the results