防止类在Python中直接实例化 [英] Preventing a class from direct instantiation in Python

查看:732
本文介绍了防止类在Python中直接实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这里是一个例子:

  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()

#结果:
#子类1
#nubclass 2
#跟踪(最近一次调用)
#文件abst.py,第28行,在< module>
#c.method_one()
#文件abst.py,第4行,在method_one
#value = self.subclass_method()
#AttributeError:'SuperClass'object没有属性'subclass_method'

我正在考虑更改 init 超类并验证对象的类型,当一个新的实例被创建时。如果对象属于超类,则会引发错误。



任何建议?



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


I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error.

Here is an example:

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'

I was thinking about changing the init of super class and verify the type of object, when a new instance is created. If the object belongs to super class raise an error. However, I'm not too sure if it's the Pythonic way of doing it.

Any recommendations?

解决方案

You're talking about Abstract Base Classes, and the Python language does not support them natively.

However, in the standard library, there is a module you can use to help you along. Check out the abc documentation.

这篇关于防止类在Python中直接实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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