我希望这个Parent
类有一个检查机制来确保它的所有子类都为属性设置一个实际值name
。我在这里找到了一些东西。
class Parent(object):
#name = None
def __init__(self):
if self.name == None:
raise NotImplementedError('Subclasses must define name')
class Child1(Parent):
pass
class Child2(Parent):
name = 'test'
class Child3(Parent):
def __init__(self):
self.name = 'test'
class Child4(Parent):
def __init__(self):
pass
#obj1 = Child1() # Expected output: NotImplementedError: Subclasses must define bar
obj2 = Child2()
obj3 = Child3()
obj4 = Child4() # I want the NotImplementedError is raised here as well, but it doesn't
问题是只要__init__
子类中有一个方法,它就会覆盖Parent
该类并且raise NotImplementedError
不再有效。
我目前的工作解决方案是:
class Child5(Parent):
def __init__(self):
self.name = 'test'
super().__init__()
obj5 = Child5()
这似乎可行,但我想知道它是否是一个正确的实现,或者它是否可能有一些隐藏的陷阱,以及我是否应该学习使用/实现@abstractproperty
而不是这个解决方案?