python中从派生类的静态成员值初始化静态成员

2024-09-26 18:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在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值所需的所有信息都存储在静态变量中。你知道吗


Tags: ofthename实体id数据库静态成员
1条回答
网友
1楼 · 发布于 2024-09-26 18:00:37

您可以使用的是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语句来检查dctdct是一个字典,它包含初始化前的类成员:因此它包含所有方法、类字段等

因此,我们检查'entityName'是否是键之一(这意味着在类级别上,它是在某个地方定义的)。如果是这样的话,我们在dct'idFieldName'中添加一个新元素,它在entityName前面加上id_。当然,您可以定义一个else案例来说明如果没有这样的属性entityName该怎么办

元类的__new__是在类的构造中执行的,而不是在对象的构造中执行的。因此,除非动态创建类,否则只能调用一次。你知道吗

相关问题 更多 >

    热门问题