Python调用类变量

时间:2019-10-15 15:57:39

标签: python

这是我第一次使用StackOverflow,因此如果我做错了事,我深表歉意。

我在使用Python(不是3)时遇到问题,我不知道如何描述它,我正在尝试通过另一个变量调用包含类的变量。

代码如下:

import random

class Weapon:
    def __init__(self, name, num, dx, dmg):
        self.name = str(name)
        self.name = self.name.lower()
        self.xd = int(num)
        self.dx = int(dx)
        self.dmg = str(dmg)
        weapon_list.append(self.name)

    def attack(self):
        #Defining Variables
        crit = None
        fail = None
        display = True
        #Ask user for AC and Bonus
        ac = int(input("What is the AC?: "))
        bon = int(input("What is the bonus?: "))
        #Roll attack
        roll_num = random.randrange(1,20,1)
        #Crit Fail Manager
        if roll_num == 1:
            fail = True
            display = False
        #Crit Manager
        elif roll_num == 20:
            print("Crit!")
            crit = True
            display = False
        #Add Bonus
        roll_num += bon
        #Print roll if not crit or fail
        if display:
            print(self.name + ": " + str(roll_num))
        #If fail print Crit Fail
        if fail:
            print("Crit Fail!")
        #Else if roll is larger than AC, roll damage
        elif roll_num >= ac:
            if not crit:
                print("Hit!")
            #Ask user for new bonus
            bon = int(input("What is the bonus?: "))
            roll_num = 0
            #Roll damage and add bonus
            for i in range(self.xd):
                roll_num += random.randrange(1,self.dx,1)
            roll_num += bon
            #If a crit, add bonus crit damage
            if crit:
                roll_num += self.dx
            #If not a fail, print damage roll
            if not fail:
                print(self.name + ": " + str(roll_num) + " " + self.dmg)
        #Miss if roll is smaller than AC
        else:
            print("Miss")

weapon_list = []
battleaxe = Weapon("Battleaxe", 1, 8, "slashing")
glaive = Weapon("Glaive", 1, 10, "slashing")

"""
This is where the problem is arising, I know what the issue is, but I don't
know how to fix it without making a giant list
"""
print("Which weapon do you wish to use?")
for i in range(len(weapon_list)):
    print(" > " + weapon_list[i].capitalize())
weapon = str(input("> "))
weapon = weapon.lower()
if weapon in weapon_list:
    print("Valid Weapon")
    for i in range(len(weapon_list)):
        if weapon == weapon_list[i]:
            print(weapon_list[i])
            weapon_list[i].attack()

我知道为什么会出现错误,武器列表[i]会调用类名称的字符串版本,而不是类所包含的变量,但是我不知道如何在不列出列表的情况下解决该问题。 if和elif语句中武器列表中的每个武器。 示例:

if weapon == glaive.name:
    glaive.attack()
elif weapon == battleaxe.name:
    battleaxe.attack()
#And so on...

这是我的问题“如何在不列出if语句列表的情况下如何调用包含类的变量”

1 个答案:

答案 0 :(得分:1)

您可以使用dict而不是以下列表来完成此操作:

weapon_dict = {}
weapon_dict = {weapon.name: weapon}

,当您获得输入时,可以将其用作:

weapon_dict[weapon_input].attack()
相关问题