如何在python中定义抽象类并强制实现变量
所以,我试图用两个变量定义一个抽象的基类,我想让任何“继承”这个基类的类都必须使用这些变量。。比如说:如何在python中定义抽象类并强制实现变量,python,Python,所以,我试图用两个变量定义一个抽象的基类,我想让任何“继承”这个基类的类都必须使用这些变量。。比如说: class AbstractBaseClass(object): foo = NotImplemented bar = NotImplemented 现在, 这将引发以下错误: class ConcreteClass(AbstractBaseClass): # here I want the developer to force create the class vari
class AbstractBaseClass(object):
foo = NotImplemented
bar = NotImplemented
现在,
这将引发以下错误:
class ConcreteClass(AbstractBaseClass):
# here I want the developer to force create the class variables foo and bar:
def __init__(self...):
self.foo = 'foo'
#error because bar is missing??
我可能用错了术语。。但基本上,我希望每个“实现”上述类的开发人员强制定义这些变量???更新:
abc.abstractproperty
在Python 3.3中已被弃用。将property
与abc.abstractmethod
一起使用,如图所示
class AbstractBaseClass(object):
def __init__(self):
assert hasattr(self, 'foo')
assert hasattr(self, 'bar')
check out
abc
提供了抽象属性(这里可能适用)和抽象方法,而不是一般的实例变量。但是为什么要在初始化阶段检查这些值,也许用户稍后会定义它们。所以我认为应该在抽象基类中将它们设置为None。当您在某些abcd方法中需要它时。如果再次出现“无”,那么您将抛出一个异常……信任对于Python编程来说是非常基本的,包括duck类型、缺少私有变量等等。即使您可以强制开发人员使用这些变量初始化类,但有什么可以阻止他们以后删除这些变量呢?这很容易通过简单地重写和不调用AbstractBaseClass来克服。此外,断言也可以关闭。python中的任何内容都可以被重写。。。如果不调用基类init,您将负责执行的操作。除了只读属性外,您可能还需要演示如何创建读写属性。添加了setter以使属性可写
class AbstractBaseClass(object):
def __init__(self):
assert hasattr(self, 'foo')
assert hasattr(self, 'bar')
import abc
class AbstractBaseClass(object):
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def foo(self):
pass
@abc.abstractproperty
def bar(self):
pass
class ConcreteClass(AbstractBaseClass):
def __init__(self, foo, bar):
self._foo = foo
self._bar = bar
@property
def foo(self):
return self._foo
@foo.setter
def foo(self, value):
self._foo = value
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, value):
self._bar = value