【发布时间】:2016-11-20 17:09:30
【问题描述】:
我想知道将我的类的私有变量设为抽象的正确方法是什么。让我总结一下我的变量的属性:
- 类变量
- 私人
- 摘要
我的课程结构如下:
from abc import ABCMeta
class AbstractClass(ABCMeta):
__private_abstract_property = None # Needs this as private abstract class variable
# ... some functions
class ParentClass(AbstractClass): # inherits `AbstractClass`
# .. some more functions
class ChildClass1(ParentClass): # inherits `ParentClass`
__private_abstract_property = 'value1' # value to be initialized here
class ChildClass2(ParentClass): # inherits `ParentClass`
__private_abstract_property = 'value2'
实现这一目标的正确方法是什么?
一种方法是使用abc.abstractproperty装饰器:
class AbstractClass(ABCMeta):
@abstractproperty
def __private_abstract_property(self):
...
或者,如Abstract Attributes in Python 的回答中所述:
class AbstractClass(ABCMeta):
__private_abstract_property = NotImplemented
我想知道实现这一目标的正确方法(欢迎任何方法,即使我提到的方法除外)。
编辑:以下是我正在尝试做的一些描述:
我有一个经理
AbstractClass,它有一些与数据库相关的集合操作。它应该是抽象的,因为我不想要这个类的任何直接对象。还有一些没有定义的功能ParentClass派生自AbstractClass。它将具有一些与从数据库中获取特定项目相关的功能。同样,这个类也不知道它正在处理的数据库。ChildClass实际上将拥有与其交互的数据库引擎。由于可能有不同的引擎拥有相同的信息,我将在此处设置连接名称并基于此连接作为源,ParentClass的函数将从数据库中获取信息。此外,ChildClass可以有除ParentClass之外的其他功能
【问题讨论】:
-
这听起来像是一个 XY Problem 尝试用 Python 编写 Java 的结果。你想完成什么任务?
-
@TigerhawkT3 对问题进行了编辑
标签: python python-2.7 abstract-class abc