Python调用variab类

2024-05-23 15:47:30 发布

您现在位置: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()

我知道为什么会出现这个错误,wearm\u list[I]调用的是类名的字符串版本,而不是类所包含的变量,但是如果不在if和elif语句中列出wearm\u list中的每个武器,我不知道如何修复它。 示例:

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

这就是我的问题“如何调用包含类的变量而不列出if语句”


Tags: nameselfifisnumlistintfail