繁体   English   中英

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

[英]Python format and validate class variable without instantiating it

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM