如何使用PyCharm继承抽象类

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

我在Python IDLE中编写了一个代码,其中包含一个抽象类和一个继承该抽象类*的类(两个类都在同一个文件夹中)。它很棒。我想将该代码复制并粘贴到PyCharm。我制作了两张卡片,一张是抽象类,一张是继承该类的类,但是我收到了这个错误:

    class Swords(Weapon):
TypeError: module.__init__() takes at most 2 arguments (3 given)

我很困惑,因为我的代码中没有任何改变。这是代码

第一张牌:武器

from abc import ABC, abstractmethod


class Weapon(ABC):

    @abstractmethod
    def __init__(self, name):
        self.name = name

第二张牌:剑

import Weapon


class Swords(Weapon):

    def __init__(self, name, attack_points, price):
        super().__init__(name)

        self.attack_points = attack_points
        self.price = price

    def info(self):
        info = self.name + " is attack-weapon that increases attack points!"
        return info

    def __str__(self):
        return "Sword name: {}\nSword attack: +{}\nSword price: {}\n".format(self.name,
                                                                             self.attack_points,
                                                                             self.price)


Elf_Sword = Swords("Elf Sword", 1, 50)
Fire_Sword = Swords("Fire Sword", 2, 80)
Space_Sword = Swords("Space Sword", 3, 120)


print(Elf_Sword)

请告诉我,我做错了什么?

python oop pycharm
2个回答
4
投票

您可能在名为Weapon的模块中有Weapon.py类,而您只是导入模块而不是类。

它是否是ABC并不重要。

作为一般命名的经验法则,

  • 一般来说,模块应该是小写的
  • 类应该是PascalCase和单数

weapon.py

class Weapon:
    pass

sword.py

from weapon import Weapon

class Sword(Weapon):
    pass

1
投票

你不能导入课程。您必须从这些模块导入模块或类。

在您的情况下,语法是

from file_where_weapon_is import Weapon
© www.soinside.com 2019 - 2024. All rights reserved.