2

クラス変数を検証してフォーマットしようとしています。クラスはクラスをそのまま拡張し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)

しかし、それから私はそれをねじりすぎていると感じます。それで、これを行う方法は?そして、私の理解は正しいですか?どんな助けでも大歓迎です。

4

1 に答える 1