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