我正在用python编写一些代码,这些代码要求实现某些抽象基类的子类的对象的属性。基于本网站上的其他帖子和建议,以及ABC中使用@property
装饰器的流行方法。但是,该方法不要求实际对象在初始化时具有该属性,只要求它在子类中实现了@property
方法
class ABCFoo(ABC):
depth= NotImplemented
@property
@abstractmethod
def someAttribute(self):
raise NotImplementedError
class Foo(ABCFoo):
def __init__(self,otherAttribute):
self._otherAttribute=otherAttribute
@property
def someAttribute(self):
return self._someAttribute
@property
def otherAttribute(self):
return self._otherAttribute
在上面的代码中Foo
类可以初始化为方法someAttribute
存在,但是调用时会引发属性错误。这可能是一个问题,如果这种情况发生在一些计算代价高昂的代码的末尾,而如果更早检测到这种情况,就可以避免
foo=Foo(3)
computationallyExpensiveMethod(foo)
foo.someAttribute
输出
AttributeError: 'Foo' object has no attribute '_someAttribute'
如果使用了@runtime_checkable
装饰器,则来自typing
的Protocol
类能够使用isinstance
检查对象中的属性,但是如果显式继承子类,仅隐式子类型,则这不起作用
有没有更好的方法来检查子类是否正在履行包含指定属性的契约
目前没有回答
相关问题 更多 >
编程相关推荐