是否可以从python (2.7)中派生类的静态成员初始化基类的静态成员?
也就是说,假设我有一组类映射存储在一个简单数据库中的实体:
class EntityA(EntityBase):
entityName = 'EntA' # the name of the entity in the DB
...
class EntityB(EntityBase):
entityName = 'EntB' # the name of the entity in the DB
...并且假设DB是按照这样的规则构建的,即所有实体都有一个id字段,名为“id_name-of-物”。因此,“id_EntA”和“id_EntB”分别是用于EntityA和EntityB的DB中id字段的名称。
现在我只想从(抽象的)基类(EntityBase)中生成这两个名称一次,但是我找不到一种方法.
我想写这样的东西:
class EntityBase:
idFieldName = 'id_' + *derived-class*.entityName
...我知道我可以编写一个返回连接字符串的简单函数,但我不希望每次调用该函数时都对它进行评估。这应该是可能的,因为构建idFieldName值所需的所有信息都存储在静态变量中。
发布于 2017-07-30 16:19:19
您可以使用的是metaclass。元类是某个类所属的类。
然后你可以使用:
class MetaEntityBase(type):
def __new__(meta, name, bases, dct):
if 'entityName' in dct:
dct['idFieldName'] = 'id_'+dct['entityName']
return super(MetaEntityBase,meta).__new__(meta,name,bases,dct)然后你可以写:
class EntityBase:
__metaclass__ = MetaEntityBase现在,如果我们查询EntityA.idFieldName,就会得到:
>>> EntityA.idFieldName
'id_EntA'在这里,我们首先使用一个if语句来检查dct。dct 是一个字典,它包含在 initialization:之前的类成员,因此它包含所有方法、类字段等。
因此,我们检查'entityName'是否是其中的一个键(这意味着在类级别上,它是在某个地方定义的)。如果是这样的话,我们将向dct添加一个新元素:'idFieldName',它在entityName前面加上id_。当然,如果没有这样的属性else,您可以为要做的事情定义一个entityName案例。
元类的__new__是在构造类时执行的,而不是对象的构造。因此,除非动态创建类,否则只能调用一次。
https://stackoverflow.com/questions/45401896
复制相似问题