Python抽象类-如何阻止实例化? [英] Python abstract classes - how to discourage instantiation?

查看:261
本文介绍了Python抽象类-如何阻止实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C#背景,该语言具有一些内置的保护开发人员"功能.我了解Python采用了我们都在这里成年"的方式,并让开发人员有责任周到仔细地编写代码.

I come from a C# background where the language has some built in "protect the developer" features. I understand that Python takes the "we're all adults here" approach and puts responsibility on the developer to code thoughtfully and carefully.

也就是说,Python建议使用约定,例如私有实例变量的前划线.我的问题是,是否存在将类标记为抽象的特定约定,而不仅仅是在文档字符串中指定该类?我在python样式指南中没有特别提及过抽象命名约定的内容课.

That said, Python suggests conventions like a leading underscore for private instance variables. My question is, is there a particular convention for marking a class as abstract other than just specifying it in the docstrings? I haven't seen anything in particular in the python style guide that mentions naming conventions for abstract classes.

到目前为止,我可以想到3种选择,但是我不确定它们是否是好主意:

I can think of 3 options so far but I'm not sure if they're good ideas:

  1. 在类上方的文档字符串中指定它(可能会被忽略)
  2. 在类名中使用前导下划线(不确定是否可以普遍理解)
  3. 在抽象类上创建def __init__(self):方法,以引发错误(不确定是否会对继承产生负面影响,例如是否要调用基构造函数)
  1. Specify it in the docstring above the class (might be overlooked)
  2. Use a leading underscore in the class name (not sure if this is universally understood)
  3. Create a def __init__(self): method on the abstract class that raises an error (not sure if this negatively impacts inheritance, like if you want to call a base constructor)

其中一种是好的选择,还是有更好的选择?我只想确保其他开发人员知道它是抽象的,因此,如果他们尝试实例化它,则应对任何奇怪的行为承担责任.

Is one of these a good option or is there a better one? I just want to make sure that other developers know that it is abstract and so if they try to instantiate it they should accept responsibility for any strange behavior.

推荐答案

如果您使用的是Python 2.6或更高版本,则可以使用

If you're using Python 2.6 or higher, you can use the Abstract Base Class module from the standard library if you want to enforce abstractness. Here's an example:

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)", "")

输出:

>>> 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.'

这篇关于Python抽象类-如何阻止实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆