简体   繁体   中英

Calling previously defined functions within other functions(Python)

I know this question has been asked a lot on this site, but for some reason no matter what I look at and try it's not helping my code. I'm working on an increasingly extensive combat algorithm for a small game, and in the object that defines all the functions that do the math I also want to have a function with a bunch of print statements that can be called in these other functions so I don't have a ton of the same print statements in every function. So, a simplified version of this would be:

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

The print function would take in arguments from the object, as well as the results of combatMath then print them out so you can see your current HP, EP, MP, etc. So, basically this comes down to being able to call a function within another function, which I can't seem to figure out. A simple explanation would be appreciated. Please let me know if I need to elaborate on this.

You're calling the builtin print instead of the one you've defined for your class. Call that one using 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

[edit]

Even if you're not using a builtin, Python still doesn't know where to look. Telling it to look in the class declaration for that method directs it to where you want it to go:

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

run with this

c = test()
c.t2()

gives the expected

"stuff and things"

as opposed to this declaration, which doesn't know where to find t1 and therefore gives a

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM