防止类在Python中直接实例化

时间:2011-11-03 00:37:41

标签: python class locking superclass

我有一个带有方法的超类,该方法调用仅在其子类中定义的其他方法。这就是为什么当我创建一个超类的实例并调用它的方法时,它找不到该方法并引发错误。

以下是一个例子:

class SuperClass(object):

  def method_one(self):
    value = self.subclass_method()
    print value


class SubClassOne(SuperClass):

  def subclass_method(self):
    return 'subclass 1'


class SubClassTwo(SuperClass):

  def subclass_method(self):
    return 'nubclass 2'


s1 = SubClassOne()
s1.method_one()

s2 = SubClassTwo()
s2.method_one()

c = SuperClass()
c.method_one()

# Results:
# subclass 1
# nubclass 2
# Traceback (most recent call last):
#   File "abst.py", line 28, in <module>
#     c.method_one()
#   File "abst.py", line 4, in method_one
#     value = self.subclass_method()
# AttributeError: 'SuperClass' object has no attribute 'subclass_method'

我在考虑更改超类的 init 并在创建新实例时验证对象的类型。如果对象属于超类引发错误。但是,我不太确定它是否是Pythonic的做法。

有什么建议吗?

4 个答案:

答案 0 :(得分:36)

我会覆盖基类中的__new__(),如果它是基类,则根本无法实例化。

class BaseClass(object):

    def __new__(cls, *args, **kwargs):
        if cls is BaseClass:
            raise TypeError("base class may not be instantiated")
        return object.__new__(cls, *args, **kwargs)

这使得关注点比在__init__()中更好地分离,并且“快速失败。”

答案 1 :(得分:18)

您的方法是典型的framework pattern

使用__init__验证type(self) is not SuperClass是确保SuperClass没有直接实例化的合理方法。

另一种常见方法是在调用时提供raise NotImplementedError的存根方法。这更可靠,因为它还验证了子类已覆盖了预期的方法。

答案 2 :(得分:10)

您正在谈论抽象基类,而Python语言本身并不支持它们。

但是,在标准库中,您可以使用一个模块来帮助您。查看abc文档。

答案 3 :(得分:9)

这就是我可能做的事情:

class SuperClass(object):
    def __init__(self):
        if type(self) == SuperClass:
            raise Exception("<SuperClass> must be subclassed.")
        # assert(type(self) == SuperClass)

class SubClass(SuperClass):
    def __init__(self):
        SuperClass.__init__(self)

subC = SubClassOne()
supC = SuperClass() # This line should throw an exception

运行时(抛出异常!):

[ 18:32 jon@hozbox ~/so/python ]$ ./preventing-direct-instantiation.py
Traceback (most recent call last):
  File "./preventing-direct-instantiation.py", line 15, in <module>
    supC = SuperClass()
  File "./preventing-direct-instantiation.py", line 7, in __init__
    raise Exception("<SuperClass> must be subclassed.")
Exception: <SuperClass> must be subclassed.

编辑(来自评论):

[ 20:13 jon@hozbox ~/SO/python ]$ cat preventing-direct-instantiation.py 
#!/usr/bin/python

class SuperClass(object):
    def __init__(self):
        if type(self) == SuperClass:
            raise Exception("<SuperClass> must be subclassed.")

class SubClassOne(SuperClass):
    def __init__(self):
        SuperClass.__init__(self)

class SubSubClass(SubClassOne):
    def __init__(self):
        SubClassOne.__init__(self)

class SubClassTwo(SubClassOne, SuperClass):
    def __init__(self):
        SubClassOne.__init__(self)
        SuperClass.__init__(self)

subC = SubClassOne()

try:
    supC = SuperClass()
except Exception, e:
    print "FAILED: supC = SuperClass() - %s" % e
else:
    print "SUCCESS: supC = SuperClass()"

try:
    subSubC = SubSubClass()
except Exception, e:
    print "FAILED: subSubC = SubSubClass() - %s" % e
else:
    print "SUCCESS: subSubC = SubSubClass()"

try:
    subC2 = SubClassTwo()
except Exception, e:
    print "FAILED: subC2 = SubClassTwo() - %s" % e
else:
    print "SUCCESS: subC2 = SubClassTwo()"

打印:

[ 20:12 jon@hozbox ~/SO/python ]$ ./preventing-direct-instantiation.py 
FAILED: supC = SuperClass() - <SuperClass> must be subclassed.
SUCCESS: subSubC = SubSubClass()
SUCCESS: subC2 = SubClassTwo()