Skip to main content
 首页 » 编程设计

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

2024年10月24日8findumars

我正在尝试验证和格式化类变量。该类使用 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 

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

class FormattingABCMeta(ABCMeta): 
    def __new__(mcl, classname, bases, dictionary): 
        # Format here, remove format_id property from RuleBase,  
        # and use FormattingABCMeta as metaclass for RuleBase. 
        return super(C, mcl).__new__(mcl, classname, bases, dictionary) 

但后来我觉得我扭曲得太多了。那么,如何做到这一点?我的理解正确吗?任何帮助 很感激。

请您参考如下方法:

不完全确定您的目标是什么,但您需要对传递 cls 的属性对象使用 fget 以获取 _id:

 print cls.format_id.fget(cls)