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
108 views
in Technique[技术] by (71.8m points)

How to call a function inside a function in Python

def diserang(self, lawan, attackPower_lawan):
    print(self.name + " Diserang " + lawan.name)
    attack_diterima = attackPower_lawan / self.armorNumber
    print("Serangan terasa :", str(attack_diterima))
    self.health -= attack_diterima
    print("Darah " + self.name + " tersisa " + str(self.health))
    

# TODO make hero attack and armor status up by 30% if the health reach by 50%
def statusUp(self, attUp, armUp):
    if self.health <= 50 :
        attUp += 30
        armUp += 30 
    else:
        raise Exception("Darah Anda Masih Normal")

i want to call the "statusUp" inside the "diserang", can anyone help me and explain it to me? im new at programming, thanks!

question from:https://stackoverflow.com/questions/66057600/how-to-call-a-function-inside-a-function-in-python

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

1 Reply

0 votes
by (71.8m points)

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.

You use inner functions to protect them from everything happening outside of the function, meaning that they are hidden from the global scope.

Here’s a simple example that highlights that concept:

def outer(num1):
def inner_increment(num1):  # Hidden from outer code
    return num1 + 1
num2 = inner_increment(num1)
print(num1, num2)

inner_increment(10)
# outer(10)

Try calling inner_increment():

Traceback (most recent call last):
File "inner.py", line 7, in <module>
inner_increment()
NameError: name 'inner_increment' is not defined

Now comment out the inner_increment() call and uncomment the outer function call, outer(10), passing in 10 as the argument:

10 11

Note: Keep in mind that this is just an example. Although this code does achieve the desired result, it’s probably better to make inner_increment() a top-level “private” function using a leading underscore: _inner_increment().


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

...