在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
...
假设数据库是按照所有实体都有一个名为'id\em>name of the entity'的id字段的规则构建的。因此,'id\u EntA'和'id\u EntB'分别是数据库中EntityA和EntityB的id字段的名称。你知道吗
现在我只想从(抽象)基类(EntityBase)生成这两个名称一次,但我找不到方法来实现它。。。你知道吗
我想写一些像:
class EntityBase:
idFieldName = 'id_' + *derived-class*.entityName
...
我知道我可以编写一个返回串联字符串的简单函数,但我不希望每次调用该函数时都对其求值。这应该是可能的,因为构建idFieldName
值所需的所有信息都存储在静态变量中。你知道吗
您可以使用的是metaclass。元类是某个类所属的类。你知道吗
然后您可以使用:
然后你可以写:
现在如果我们查询
EntityA.idFieldName
,我们得到:这里我们首先使用
if
语句来检查dct
。dct
是一个字典,它包含初始化前的类成员:因此它包含所有方法、类字段等因此,我们检查
'entityName'
是否是键之一(这意味着在类级别上,它是在某个地方定义的)。如果是这样的话,我们在dct
:'idFieldName'
中添加一个新元素,它在entityName
前面加上id_
。当然,您可以定义一个else
案例来说明如果没有这样的属性entityName
该怎么办元类的
__new__
是在类的构造中执行的,而不是在对象的构造中执行的。因此,除非动态创建类,否则只能调用一次。你知道吗相关问题 更多 >
编程相关推荐