我正在创建一个抽象类,我希望其所有继承都保存一个具有确切名称的X类型对象。
查看示例:
from abc import ABC, abstractmethod
class Hands(object):
pass
class human(ABC):
def __init__(self):
self.hand=Hands()
@property
def Hands(self):
pass
class american_hands(Hands):
pass
#I want to make sure that a class of type human will have a member of type hands which is called hand
class american(human):
def __init__(self):
self.hand=american_hands()
如何强制人类类的后代持有具有预定义名称的所需类型的成员?
例如,我希望没有class.hand.self.hand的实现类human
的任何人都会引发错误,例如:
class German(Human):
def __init__(self):
super().__init__()
不行。
答案 0 :(得分:2)
也许类似
class Hands:
pass
class AmericanHands(Hands):
pass
class Human:
hand_type = Hands
def __init__(self):
self.hands = self.hand_type()
class American(Human):
hand_type = AmericanHands
def __init__(self):
super().__init__()
# Other American-specific initialization
h = Human() # assert isinstance(h.hands, Hands)
a = American() # assert isinstance(a.hands, AmericanHands)
对super().__init__
的调用可确保American
的实例具有名为hands
的属性,而override class属性可确保hands
的类型正确。 / p>