gpt4 book ai didi

python - 如何在python中定义一个抽象类并强制实现变量

转载 作者:太空狗 更新时间:2023-10-30 02:29:54 25 4
gpt4 key购买 nike

所以,我试图用几个变量定义一个抽象基类,我想强制要求任何“继承”这个基类的类都必须拥有这些变量。所以,像这样:

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'
self.bar = 'bar'

这应该会抛出错误:

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 中弃用。将 propertyabc.abstractmethod 结合使用,如图所示 here .

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

关于python - 如何在python中定义一个抽象类并强制实现变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com