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

所以,我试图定义一个带有几个变量的抽象基类,我想让它对任何“继承”这个基类的类都必须要有.所以,类似于:

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中弃用.使用带有abc.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

来源: https://codeday.me/bug/20190528/1170538.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值