基于UML类图创建代码,给我一个错误

问题描述 投票:0回答:1

我有一个 UML 图并编写了这段代码..我正确地解释了它吗?我不确定武器类部分。我得到的建议是武器不会继承铁匠.. 这是我的代码:

class Character:
    def __init__(self, namestring):
        self.name = namestring
        self.health = 100
        self.type = ''
    def __str__(self): #string operation
        return f"Name: {self.name}\nHealth: {self.health}\n Type: {self.type}"

class Blacksmith(Character):
    def __init__(self, weapon):
        super().__init__(name)
        super().__init__(health)
        self.weapon = weapon
        self.type = 'blacksmith'
        
class Weapon:
    def __init__(self, name, Type, damage):
        self.name = name
        self.type = Type
        self.damage = damage
#testing the code
w = Weapon('stygius', 'stygian blade', 63)
b = Blacksmith("sword")
print(b)

我有这个错误

NameError                                 Traceback (most recent call last)
<ipython-input-14-dc0ac5ca43ff> in <module>()
      1 #test class instantiation
      2 w = Weapon('stygius', 'stygian blade', 63)
----> 3 b = Blacksmith("sword")
      4 print(b)

<ipython-input-13-536a28d9bb79> in __init__(self, weapon)
      9 class Blacksmith(Character):
     10     def __init__(self, weapon):
---> 11         super().__init__(name)
     12         super().__init__(health)
     13         self.weapon = weapon

NameError: name 'name' is not defined
python class inheritance
1个回答
0
投票

我不知道为什么没有人尝试帮助这个家伙。只需要5分钟的写作时间。这是我对你问题的回答,可怜的朋友。

class Character:
def __init__(self, namestring):
    self.name = namestring
    self.health = 100
    self.type = ''
    self.weapons = []
def __str__(self): #string operation
    return f"Name: {self.name}\nHealth: {self.health}\nType: {self.type}"

class Blacksmith(Character):
    def __init__(self, name, weapon):
        super().__init__(name)
        self.weapon = weapon
        self.type = 'blacksmith'
    def registerWeapon(self, weapon):
        self.weapons.append(weapon)
    def __str__(self):
        character_info = super().__str__()
        weapons_info = ""
        for x in self.weapons:
            weapons_info  += f"Name: {x.name}, Type: {x.type}, Damage: {x.damage} \n"
        return f"Blacksmith: {character_info}, \nwith weopons: \n{weapons_info}"
        
class Weapon:
    def __init__(self, name, Type, damage):
        self.name = name
        self.type = Type
        self.damage = damage

#testing the code
w1 = Weapon('Stygius D', 'Dagger', 20)
w2 = Weapon('Stygius B', 'Blade', 63)
w3 = Weapon('Stygius GS','Great Sword', 84)
b = Blacksmith("AsmonGold", "sword")
b.registerWeapon(w1)
b.registerWeapon(w2)
b.registerWeapon(w3)
print(b)

我希望这个答案能对某人的追求有所帮助。
顺便说一下,这个问题假设 Blachsmith 是一个角色,并且他有武器可以出售。

© www.soinside.com 2019 - 2024. All rights reserved.