为什么要在抽象类的__init__方法中添加一个抽象方法作为属性?

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

我正在读一本关于Python设计模式的书。 当我看到有关“工厂”模式的代码时,我感到有点困惑。

class Profile(metaclass=ABCMeta):
    def __init__(self):
        self.sections = []
        **self.create_profile()**

    @abstractmethod
    def **create_profile**(self):
        pass

    def get_section(self):
        return self.sections

方法create_profile是一个抽象方法,它被添加到init方法中。 请让我澄清为什么这样做。

非常感谢

python-3.x abstract-class
1个回答
0
投票
  • 这意味着当你编写子类继承
    Profile
    时,你必须重写
    abstract method

具有从 ABCMeta 派生的元类的类无法实例化,除非覆盖其所有抽象方法。

示例代码:

from abc import ABCMeta, abstractmethod
class Profile(metaclass=ABCMeta):
    def __init__(self):
        self.sections = []
        self.create_profile()

    @abstractmethod
    def create_profile(self):
        pass

    def get_section(self):
        return self.sections
    
class SubProfile(Profile):
    def __init__(self):
       self.create_profile()

    def create_profile(self):
        self.sections = [1,2,3]

class AnotherSubProfile(Profile):
    def __init__(self):
       self.create_profile()

    def create_profile(self):
        self.sections = [4,5,6]

class NoCreateSubProfile(Profile):
    def __init__(self):
       self.sections = [7,8,9]
    
sub = SubProfile()
print(sub.get_section())
sub = AnotherSubProfile()
print(sub.get_section())
sub = NoCreateSubProfile()
print(sub.get_section())

结果:

[1, 2, 3]
[4, 5, 6]
TypeError: Can't instantiate abstract class NoCreateSubProfile with abstract method create_profile
© www.soinside.com 2019 - 2024. All rights reserved.