我创建了一个方法,根据特定条件为局部变量赋值。我想将该值转换为函数外部的变量,以便在其他地方使用它。这是我正在进行的文字冒险。
class Player(object):
def __init__(self, player_name):
self.player_name = player_name
def JobType(self):
print("Please select your job:")
print(" ")
print("1. name1")
print("2. name2")
print("3. name3")
print("4. name4")
global jobChoice
jobChoice = input()
jobs = ["name1", "name2", "name3", "name4"]
if jobChoice == 1:
jobChoice = jobs[0]
elif jobChoice == 2:
jobChoice = jobs[1]
elif jobChoice == 3:
jobChoice = jobs[2]
elif jobChoice == 4:
jobChoice = jobs[3]
else:
print "Invalid job"
print("You are now a " + jobChoice)
return jobChoice
def JobStats(self):
playerHP = 0
playerAttack = 0
playerDefense = 0
playerLuck = 0
if jobChoice == "name1":
playerHP = random.randint(70, 85)
playerAttack = random.randint(6, 9)
playerDefense = random.randint(6, 11)
playerLuck = random.randint(14, 17)
elif jobChoice == "name2":
playerHP = random.randint(70, 85)
playerAttack = random.randint(7, 10)
playerDefense = random.randint(6, 11)
playerLuck = random.randint(3, 6)
elif jobChoice == "name3":
playerHP = random.randint(120, 200)
playerAttack = random.randint(200, 600)
playerDefense = random.randint(6, 11)
playerLuck = random.randint(200, 600)
elif jobChoice == "name4":
playerHP = random.randint(70, 85)
playerAttack = random.randint(8, 11)
playerDefense = random.randint(6, 11)
playerLuck = random.randint(7, 10)
return(playerHP, playerAttack, playerDefense, playerLuck)
此外, jobChoice 是全球。我不希望这样,但这也是我提取其他函数中使用的局部变量值的问题的一部分。
因此,如果我想要一个新的 playerLuck 变量与方法中的本地 playerLuck 变量具有相同的值, jobStats ,怎么会我开始获得这个价值了吗? :
playerLuck = ?
答案 0 :(得分:1)
“提取局部变量的值”应该以两种方式之一完成;之一:
return
该变量;或Class.attribute
或instance.attribute
。由于您已有课程,因此您可以轻松拥有实例属性self.jobChoice
和self.playerLuck
。然后您可以轻松访问它们:
player = Player(...)
...
if player.jobChoice ...: