Python AttributeError:类型对象'x'没有属性'x'

Jam*_*ips 3 python debugging

我目前正在研究一个简单的基于文本的Python游戏,只是为了练习python和面向对象的编程,但我遇到了这个错误,它告诉我'LargeManaPotion'没有属性'name',当我看到它确实如此,它的声明方式与'SmallManaPotion'完全相同.我假设这是一个愚蠢的错误,我只是在俯视或者什么但是会很感激帮助.此外,当我在player.inventory函数中打印播放器的库存时,程序将打印药水,所以我不确定为什么它在交易功能中不起作用.无论如何,这是相关的代码.提前致谢.

class ManaPotion:
    def __init__(self):
        raise NotImplementedError("Do not create raw ManaPotion objects.")

    def __str__(self):
        return "{} (+{} Mana)".format(self.name, self.mana_value)


class LargeManaPotion(ManaPotion):
    def __init__(self):
        self.name = "Large Mana Potion"
        self.mana_value = 45
        self.value = 40


class SmallManaPotion(ManaPotion):
    def __init__(self):
        self.name = "Small Mana Potion"
        self.mana_value = 15
        self.value = 10
Run Code Online (Sandbox Code Playgroud)

如您所见,它与SmallManaPotion相同.这是导致错误的函数.

class TraderTile(MapTile):
def intro_text(self):
    return "A frail not-quite-human, not-quite-creature squats in the corner " \
           "\nclinking his gold coins together. \nHe looks willing to trade."

def __init__(self, x, y):
    self.trader = npc.Trader()
    super().__init__(x, y)

def trade(self, buyer, seller):
    for i, item in enumerate(seller.inventory, 1):
#the line below here is where I'm getting the error.
        print("{}. {} - {} Gold".format(i, item.name, item.value))
    while True:
        user_input = input("Choose an item or press Q to exit: ")
        if user_input in ['q', 'Q']:
            return
        else:
            try:
                choice = int(user_input)
                to_swap = seller.inventory[choice - 1]
                self.swap(seller, buyer, to_swap)
            except ValueError:
                print("Invalid choice!")

def swap(self, seller, buyer, item):
    if item.value > buyer.gold:
        print("That's too expensive.")
        return
    seller.inventory.remove(item)
    buyer.inventory.append(item)
    seller.gold = seller.gold + item.value
    buyer.gold = buyer.gold - item.value
    print("Trade complete!")

def check_if_trade(self, player):
    while True:
        print("\n\nGold: {} \nWould you like to (B)uy, (S)ell, or (Q)uit?".format(player.gold))
        user_input = input()
        if user_input in ['Q', 'q']:
            return
        elif user_input in ['B', 'b']:
            print("\n\nGold: {} \nHere's whats available to buy: ".format(player.gold))
            self.trade(buyer=player, seller=self.trader)
        elif user_input in ['S', 's']:
            print("\n\nGold: {} \nHere's what's available to sell: ".format(player.gold))
            self.trade(buyer=self.trader, seller=player)
        else:
            print("Invalid choice!")
Run Code Online (Sandbox Code Playgroud)

但是,此函数调用LargeManaPotion但没有任何错误.

def print_inventory(self):
    print("Inventory:")
    for item in self.inventory:
        print('* ' + str(item))
    print("* Gold: {}".format(self.gold))
    best_weapon = self.most_powerful_weapon()
    print("Your best weapon is your {}".format(best_weapon))
Run Code Online (Sandbox Code Playgroud)

错误和堆栈跟踪:

Choose an action: 
i: Print inventory
t: Trade
n: Go north
s: Go south
w: Go west
m: Replenish Mana
Action: t


Gold: 33 
Would you like to (B)uy, (S)ell, or (Q)uit?
>>>b

Gold: 33 
Here's whats available to buy: 
1. Crusty Bread - 12 Gold
2. Crusty Bread - 12 Gold
3. Crusty Bread - 12 Gold
4. Healing Potion - 60 Gold
5. Healing Potion - 60 Gold
6. Small Mana Potion - 10 Gold
7. Small Mana Potion - 10 Gold

Traceback (most recent call last):

File "/Users/Cpt_Chirp/Documents/Escape/game.py", line 74, in <module>
play()

File "/Users/Cpt_Chirp/Documents/Escape/game.py", line 17, in play
choose_action(room, player)

File "/Users/Cpt_Chirp/Documents/Escape/game.py", line 30, in choose_action
action()

File "/Users/Cpt_Chirp/Documents/Escape/player.py", line 112, in trade
room.check_if_trade(self)

File "/Users/Cpt_Chirp/Documents/Escape/world.py", line 127, in check_if_trade
self.trade(buyer=player, seller=self.trader)

File "/Users/Cpt_Chirp/Documents/Escape/world.py", line 96, in trade
print("{}. {} - {} Gold".format(i, item.name, item.value))
AttributeError: type object 'LargeManaPotion' has no attribute 'name'

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

en_*_*ght 5

我不相信你提供了正确的代码,但是你已经提供了足够的信息来确定这里发生了什么

a = list()
b = list
a.append(1)
b.append(1)
Run Code Online (Sandbox Code Playgroud)

哪一个会引发错误?显然,追加b.虽然"list"类型的对象具有方法"append",但基类"Type List"却没有.

在某处,您已将类型分配LargeManaPotion给变量并尝试从中访问该字段name.但类型本身没有那些字段.你可以这样做的原因是因为在python中,类是第一类对象,可以像任何其他对象一样传递


让我们看看更接近您的实时代码的内容

class Pot(object):
    def add(self):pass

pots = [Pot(), Pot(), Pot(), Pot(), Pot]
for pot in pots: pots.add()
Run Code Online (Sandbox Code Playgroud)

现在问题在哪里?它们都是实例Pot,不是吗?为什么只有最后一个引发AttributeError?

当然,因为它们并非完全相同.前4项是Pot类的实例.从方法返回__new__,在类type Pot中定义,当我在变量名后面使用"括号表示法"时调用该类.在运行时,python不知道变量"Pot"是什么.它碰巧是一个类型变量,谁的调用生成一个实例对象.

最后一项是"类型Pot"类的实例.它不是一个锅.这是一种类型.它的__class__属性不是Pot.它的__class__属性是类型类型用于生成实例."添加"到一个类型是没有意义的.


假设你在现实生活中有魔药.你可以用药水做事.你可以喝它们.你可以检查他们的沸点(如果他们有标签,或者可能通过科学).

相反,让我们说你有一个药水的配方躺在周围.而且你说:"喝配方"."配方的沸点是什么".宇宙正在回应:"那是未定义的".你想看看魔药.相反,你看了它的食谱.像所有OO比喻一样,这个比喻是不完整的.补充阅读:

  • 哇.是的,你是完全正确的,我在Trader npc类中有一个typer,我添加了一个LargeManaPotion而不是LargeManaPotion().直到我看完你的评论然后去仔细检查,我才从未看过那​​里.我只是假设它是在LargeManaPotion初始化程序中,因为我(错误地)假设其他一切都是相同的.感谢您的快速反应. (2认同)