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

标签 python class metaprogramming abc

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

关于Python 格式化并验证类变量而不实例化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105152/

相关文章:

java - 对象无法访问定义为公共(public)的方法

c++ - 如何在编译时查询一个类的所有基类?

javascript - JavaScript 中有没有一种方法可以实例化不一定是函数的对象?

python - 用步幅组成 numpy 数组

python - 如何定义类何时为空

python - 替换实例方法

c - 将 JSON 转换为 C 结构的工具?

python - 在 django 中基于类的 View 更新后重定向用户

java - 带有 python 后端的 Android 应用程序

python - 如何使用 python 中的 selenium 将图像上传到该网站