python抽象类可以实例化吗_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.

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.

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

Specify it in the docstring above the class (might be overlooked)

Use a leading underscore in the class name (not sure if this is universally understood)

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.

解决方案

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

Output:

>>> a = SomeAbstractClass()

Traceback (most recent call last):

File "", line 1, in

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值