我正在读一本关于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方法中。 请让我澄清为什么这样做。
非常感谢
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