![](/img/trans.png)
[英]How to define a global variable before a function, then refer to it within the function in python?
[英]using a global variable before and within a function in python
我正在制作一個文本風格的冒險游戲,並且對 python 沒有太多了解。我正在嘗試使用我的 (enemyHealth),它分配了一個隨機的 integer。 我已將此變量設置為全局變量,我想在我的 function 中使用它。但是在創建 function 之前,我想打印出 function 之外的變量。我希望它們具有相同的值,但不確定是什么我應該做的。 我指的 function 是我的 (attack_function())。
這是我的代碼的一部分。
#enemy
enemyEasy = ["goblin archer", "thieves", "ghouls", "goblin swordsman"]
encounter = random.choice(enemyEasy)
global enemyHealth
enemyHealth = random.randint(9, 13)
#attack functions
attackLow = ("attack")
pursuadeDown = ("pursuade")
fleeDown = ("flee")
options = ["Attack", "Pursuade", "Flee"]
#conditions for correct grammar
if (encounter == enemyEasy[1]) or (encounter == enemyEasy[2]):
print ("\nYou walk down a path isolated when you are approached by a group of figures in the distance")
time.sleep(2)
print ("\nThe figures is a group of " + encounter + "!")
time.sleep(2)
else:
print ("\nYou walk down a path isolated when you are approached by a figure in the distance")
time.sleep(2)
print ("\nThe figure is a " + encounter + "!")
time.sleep(2)
#first encounter
print ("\nEnemy Health:", enemyHealth)
time.sleep(1)
print("\nWhat do you do?: ")
print (options)
action = input()
#attack function
def attack_function():
while (enemyHealth > 0):
if (enemyHealth > 0):
#miss function
missChance = random.randint(1,8)
if (missChance > 6):
print ("You attack the enemy and miss\n")
time.sleep(3)
else:
#random user damage from 1 - 6
userDamage = random.randint(1, 6)
print ("You attack the", encounter, "and did", userDamage, "damage!")
enemyHealth = (enemyHealth - userDamage)
print ("Enemy Health:", enemyHealth, "\n")
time.sleep(2)
if (enemyHealth > 0):
missChance = random.randint(1,8)
if (missChance > 6):
print("The enemy attacks you and misses\n")
time.sleep(3)
else:
#random enemy damage from 3 - 4
enemyDamage = random.randint(3, 4)
print ("The enemy attacked you and did", enemyDamage, "damage!")
health = (health - enemyDamage)
print ("Health:", health, "\n")
time.sleep(3)
else:
#XP System
xpGain = random.randint(2, 4)
XP = (XP + xpGain)
#enemy defeat
print ("\nYou defeated the enemy!")
print ("You gained", xpGain, "XP!")
if (XP == 10):
level = (level + 1)
print("you are now level 2")
userDamage = (random.randint(1, 6) + 3)
print ("XP:",XP)
break
#if action is to attack use attack function
if (action == options[0]) or (action == attackLow):
attack_function()
我可以建議使用課程嗎?
import random
class Enemy:
def __init__(self) -> None:
self.type = random.choice(["goblin archer", "thieves", "ghouls", "goblin swordsman"])
self.health = random.randint(9, 13)
然后,您可以將前 4 行(#enemy 下的所有內容)替換為:
enemy = Enemy()
這假設您已經從另一個文件導入 Enemy 或將 Enemy class 放在最頂部。 然后你可以訪問,更新等,health with enemy.health
編輯:僅供參考,只要在最頂層的 scope 中定義enemy
(在所有函數之外),就不需要在此處使用全局關鍵字。
編輯: self
指的是 object。您只能在__init__
function 中使用 self,然后使用您想要的任何變量名。 對於你的情況:
import random
class Enemy:
def __init__(self) -> None:
self.type = random.choice(["goblin archer", "thieves", "ghouls", "goblin swordsman"])
self.health = random.randint(9, 13)
enemy = Enemy()
#attack functions
attackLow = ("attack")
pursuadeDown = ("pursuade")
fleeDown = ("flee")
options = ["Attack", "Pursuade", "Flee"]```
global
的工作方式與您預期的不同。 您不在 python 中聲明變量,它們是在分配時動態創建的。 在全局模塊級別,將 go 分配給全局命名空間。
但在 function 中是不同的。 分配到本地 function 命名空間。 這就是global
發揮作用的地方。global 在global
中用於覆蓋此規則。 它告訴單個 function 對變量的賦值應該 go 到全局封閉命名空間,而不是本地。
所以 - 在 function 中使用global
,不要在全局命名空間中使用它。
你的代碼有一堆與問題無關的東西。 Python 使實驗變得容易,並且有助於將更大的問題轉化為簡單的示例。
enemyHealth = 1
print("health in global", enemyHealth)
def attach_function():
print("health in function", enemyHealth)
global enemyHealth
enemHealth = 99
attach_function()
print("health in global", enemyHealth)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.