Kiv*_*Kiv 47 python abstract-class
在Python 2.x中,当您想要将方法标记为抽象时,您可以像这样定义它:
class Base:
def foo(self):
raise NotImplementedError("Subclasses should implement this!")
Run Code Online (Sandbox Code Playgroud)
然后,如果您忘记覆盖它,您会收到一个很好的提醒异常.是否有相同的方法将字段标记为抽象?或者在类docstring中说明它你能做什么?
起初我以为我可以将字段设置为NotImplemented,但是当我查看它的实际内容(丰富的比较)时,它似乎是侮辱性的.
Eva*_*ark 49
是的你可以.使用@property装饰器.例如,如果你有一个名为"example"的字段,那么你不能做这样的事情:
class Base(object):
@property
def example(self):
raise NotImplementedError("Subclasses should implement this!")
Run Code Online (Sandbox Code Playgroud)
运行以下产生NotImplementedError就像你想要的一样.
b = Base()
print b.example
Run Code Online (Sandbox Code Playgroud)
Gle*_*ard 33
替代答案:
@property
def NotImplementedField(self):
raise NotImplementedError
class a(object):
x = NotImplementedField
class b(a):
# x = 5
pass
b().x
a().x
Run Code Online (Sandbox Code Playgroud)
这就像Evan一样,但简洁又便宜 - 你只会获得一个NotImplementedField实例.
一个更好的方法是使用抽象基类:
import abc
class Foo(abc.ABC):
@property
@abc.abstractmethod
def demo_attribute(self):
raise NotImplementedError
@abc.abstractmethod
def demo_method(self):
raise NotImplementedError
class BadBar(Foo):
pass
class GoodBar(Foo):
demo_attribute = 'yes'
def demo_method(self):
return self.demo_attribute
bad_bar = BadBar()
# TypeError: Can't instantiate abstract class BadBar \
# with abstract methods demo_attribute, demo_method
good_bar = GoodBar()
# OK
Run Code Online (Sandbox Code Playgroud)
请注意,您仍然应该拥有raise NotImplementedError而不是类似的东西pass,因为没有什么可以阻止继承类调用super().demo_method(),并且如果抽象demo_method只是pass,则这将无声地失败。
| 归档时间: |
|
| 查看次数: |
30308 次 |
| 最近记录: |