Lan*_*och 17 python abstract-class naming-conventions
我来自C#背景,其中语言有一些内置的"保护开发人员"功能.据我所知,Python采用"我们都是成年人"的方法,并对开发人员负责,认真细致地编写代码.
也就是说,Python建议使用惯例作为私有实例变量的前导下划线.我的问题是,除了在文档字符串中指定类之外,是否存在将类标记为抽象的特定约定? 我没有在python样式指南中看到任何特别提到的抽象类的命名约定.
到目前为止,我可以想到3个选项,但我不确定它们是否是好主意:
def __init__(self):
在抽象类上创建一个引发错误的方法(不确定这是否会对继承产生负面影响,就像要调用基础构造函数一样)其中一个是好的选择还是有更好的选择?我只是想确保其他开发人员知道它是抽象的,所以如果他们试图实例化它们,他们应该对任何奇怪的行为承担责任.
Blc*_*ght 21
如果您使用的是Python 2.6或更高版本,则可以使用标准库中的Abstract Base Class模块来强制抽象.这是一个例子:
from abc import ABCMeta, abstractmethod
class SomeAbstractClass(object):
__metaclass__ = ABCMeta
@abstractmethod
def this_method_must_be_overridden(self):
return "But it can have an implementation (callable via super)."
class ConcreteSubclass(SomeAbstractClass):
def this_method_must_be_overridden(self):
s = super(ConcreteSubclass, self).this_method_must_be_overridden()
return s.replace("can", "does").replace(" (callable via super)", "")
Run Code Online (Sandbox Code Playgroud)
输出:
>>> a = SomeAbstractClass()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a = SomeAbstractClass()
TypeError: Can't instantiate abstract class SomeAbstractClass with abstract
methods this_method_must_be_overridden
>>> c = ConcreteSubclass()
>>> c.this_method_must_be_overridden()
'But it does have an implementation.'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10420 次 |
最近记录: |