Python:通过调用同名的局部变量来定义新变量

时间:2014-01-25 23:00:44

标签: python

我创建了一个方法,根据特定条件为局部变量赋值。我想将该值转换为函数外部的变量,以便在其他地方使用它。这是我正在进行的文字冒险。

    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 = ?

1 个答案:

答案 0 :(得分:1)

“提取局部变量的值”应该以两种方式之一完成;之一:

  1. 明确return该变量;或
  2. 将其设为类或实例属性,以便可以访问Class.attributeinstance.attribute
  3. 由于您已有课程,因此您可以轻松拥有实例属性self.jobChoiceself.playerLuck。然后您可以轻松访问它们:

    player = Player(...)
    ...
    if player.jobChoice ...: