Python格式化并验证类变量而不实例化i

2024-06-01 06:10:15 发布

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

我正在尝试验证和格式化一个类变量。这个类用ABCMeta作为它的__metaclass__来扩展一个类,我还不能实例化我的子类。所以当我运行下面的代码时,它打印属性对象而不是 我想要的输出,我明白为什么。但我该怎么做呢?

from abc import ABCMeta, abstractproperty

class RuleBase(object):
    __metaclass__ = ABCMeta

    id = None
    id = abstractproperty(id)

    @property
    def format_id(self):
        try:
            _id = 'R%02d' % self.id
        except TypeError:
            raise TypeError("ID must be an integer")
        return _id

    @classmethod
    def verbose(cls):
        print cls.format_id

class Rule(RuleBase):
    id = 1

Rule.verbose()  # prints property object and not R01

根据我的理论,我认为这是可行的。

^{pr2}$

但后来我觉得我扭得太厉害了。那么,怎么做呢?我的理解正确吗?有什么帮助吗 很感激。


Tags: selfidformatverboseobjectdefpropertyrule
1条回答
网友
1楼 · 发布于 2024-06-01 06:10:15

不完全确定您的目标是什么,但是您需要对传递cls的property对象使用fget来获取id

 print cls.format_id.fget(cls)

相关问题 更多 >