質問

このコードに「機能するだけ」したい:

def main():
    c = Castable()
    print c/3
    print 2-c
    print c%7
    print c**2
    print "%s" % c
    print "%i" % c
    print "%f" % c

もちろん、簡単な方法は書くことです int(c)/3, 、ただし、構成ミニ言語用のよりシンプルなPerl-isの構文を有効にしたいと思います。

「古いスタイルの」クラスを使用している場合(オブジェクトから継承しないでください)、これを簡単に定義することでこれを行うことができます。 __coerce__ 方法ですが、古いスタイルのクラスは非推奨であり、Python3で削除されます。

新しいスタイルのクラスで同じことをすると、このエラーが発生します。

TypeError: unsupported operand type(s) for /: 'Castable' and 'int'

私はこれがデザインによるものだと思いますが、それから古いスタイルをシミュレートするにはどうすればよいですか __coerce__ 新しいスタイルのクラスでの行動?以下の私の現在のソリューションを見つけることができますが、それは非常に醜くて長いです。

これは関連するドキュメントです:(私が思う)

ボーナスポイント:

    print pow(c, 2, 100)
役に立ちましたか?

解決 2

これは機能し、いくつかの改善(@JChlへの小道具)の後には粗雑になりますが、特に「古いスタイルの」クラスでこれを無料で入手できることを考えると、まだ不必要であるべきだと思われます。

私はまだより良い答えを探しています。より良い方法がなければ、これはPython言語の回帰のように思えます。

def ops_list():
    "calculate the list of overloadable operators"
    #<type 'object'> has functions but no operations
    not_ops = dir(object)

    #calculate the list of operation names
    ops = set()
    for mytype in (int, float, str):
        for op in dir(mytype):
            if op.endswith("__") and op not in not_ops:
                ops.add(op)
    return sorted(ops)

class MetaCastable(type):
    __ops = ops_list()

    def __new__(mcs, name, bases, dict):
        #pass any undefined ops to self.__op__
        def add_op(op):
            if op in dict:
                return
            fn = lambda self, *args: self.__op__(op, args)
            fn.__name__ = op
            dict[op] = fn

        for op in mcs.__ops:
            add_op( op )
        return type.__new__(mcs, name, bases, dict)


class Castable(object):
    __metaclass__ = MetaCastable
    def __str__(self):
        print "str!"
        return "<Castable>"
    def __int__(self):
        print "int!"
        return 42
    def __float__(self):
        print "float!"
        return 2.718281828459045

    def __op__(self, op, args):
        try:
            other = args[0]
        except IndexError:
            other = None
        print "%s %s %s" % (self, op, other)
        self, other = coerce(self, other)
        return getattr(self, op)(*args)

    def __coerce__(self, other):
        print "coercing like %r!" % other
        if other is None: other = 0.0
        return (type(other)(self), other)

他のヒント

定義する必要があります __div__ お望みならば c/3 働くために。 Pythonは、最初にオブジェクトを数字に変換しません。

class MetaCastable(type):
    __binary_ops = ( 
            'add', 'sub', 'mul', 'floordiv', 'mod', 'divmod', 'pow', 'lshift', 
            'rshift', 'and', 'xor', 'or', 'div', 'truediv',
    )

    __unary_ops = ( 'neg', 'pos', 'abs', 'invert', )

    def __new__(mcs, name, bases, dict):
        def make_binary_op(op):
            fn = lambda self, other: self.__op__(op, other)
            fn.__name__ = op
            return fn

        for opname in mcs.__binary_ops:
            for op in ( '__%s__', '__r%s__' ):
                op %= opname
                if op in dict:
                    continue
                dict[op] = make_binary_op(op)

        def make_unary_op(op):
            fn = lambda self: self.__op__(op, None)
            fn.__name__ = op
            return fn

        for opname in mcs.__unary_ops:
            op = '__%s__' % opname
            if op in dict:
                continue
            dict[op] = make_unary_op(op)

        return type.__new__(mcs, name, bases, dict)

class Castable(object):
    __metaclass__ = MetaCastable
    def __str__(self):
        print "str!"
        return "<Castable>"
    def __int__(self):
        print "int!"
        return 42
    def __float__(self):
        print "float!"
        return 2.718281828459045

    def __op__(self, op, other):
        if other is None:
            print "%s(%s)" % (op, self)
            self, other = coerce(self, 0.0)
            return getattr(self, op)()
        else:
            print "%s %s %s" % (self, op, other)
            self, other = coerce(self, other)
            return getattr(self, op)(other)

    def __coerce__(self, other):
        print "coercing like %r!" % other
        return (type(other)(self), other)
class Castable(object):
    def __div__(self, other):
        return 42 / other

新しいスタイルのクラスは、古いスタイルのクラスよりも速く、より正確に動作します。したがって、これ以上高価ではありません __getattr__, __getattribute__ , __coerce__ 安価な理由と疑わしい順序で呼びかけます。

古いスタイル __coerce__ また、いくつかの特別な目的のためにオペレーター方法をすでに過負荷にしている場合でも、それが呼ばれたという問題がありました。また、共通のタイプと等しいキャストを要求し、特定のバイナリOPSに限定されます。 int / float / stringの他のすべてのメソッドとプロパティについて考えてください - およびpow()について。これらすべての制限のため coerce PY3にはありません。質問の例は、かなり幅広い仮想化を目指しています。

新しいスタイルのクラスでは、ほとんどコードで多くの「類似の」メソッドを提供するループ、またはそれらの呼び出しを仮想ハンドラーにルーティングし、その後、正確かつ正確に定義され、正確で細かい粒子化された方法でサブ分類可能です。それは「Python言語の回帰」ではありません。

ただし、そのようなループだけで、または単純な基本クラスのような動作を提供するためだけに他の回答に示されているように、私はメタクラスを使用しません。それはスレッジハンマーでナッツを割ることになるでしょう。


ここに、「バリアント」の仮想化のためのヘルパーの例:

def Virtual(*methods):
    """Build a (new style) base or mixin class, which routes method or
    operator calls to one __virtualmeth__ and attribute lookups to
    __virtualget__ and __virtualset__ optionally.

    *methods (strings, classes): Providing method names to be routed
    """
    class VirtualBase(object):  
        def __virtualmeth__(self, methname, *args, **kw):
            raise NotImplementedError
    def _mkmeth(methname, thing):
        if not callable(thing):
            prop = property(lambda self:self.__virtualget__(methname),
                            lambda self, v:self.__virtualset__(methname, v))
            return prop
        def _meth(self, *args, **kw):
            return self.__virtualmeth__(methname, *args, **kw)
        _meth.__name__ = methname
        return _meth
    for m in methods:
        for name, thing in (isinstance(m, str) and
                            {m:lambda:None} or m.__dict__).items():
            if name not in ('__new__', '__init__', '__setattr__', ##'__cmp__',
                            '__getattribute__', '__doc__', ):   ##'__getattr__', 
                setattr(VirtualBase, name, _mkmeth(name, thing))
    return VirtualBase

そして、ここにユースケースの例:anaphor! (PY2およびPY3):

import operator
class Anaphor(Virtual(int, float, str)):   
    """remember a sub-expression comfortably:

    A = Anaphor()      # at least per thread / TLS
    if re.search(...) >> A:
        print(A.groups(), +A)
    if A(x % 7) != 0:
        print(A, 1 + A, A < 3.0, A.real, '%.2f' % A, +A)
    """
    value = 0
    def __virtualmeth__(self, methname, *args, **kw):
        try: r = getattr(self.value, methname)(*args, **kw)
        except AttributeError:
            return getattr(operator, methname)(self.value, *args, **kw)
        if r is NotImplemented: # simple type -> coerce
            try: tcommon = type(self.value + args[0])    # PY2 coerce
            except: return NotImplemented
            return getattr(tcommon(self.value), methname)(*args, **kw)
        return r
    def __call__(self, value):   
        self.value = value
        return value
    __lshift__ = __rrshift__ = __call__     # A << x;  x >> A
    def __pos__(self):                      # real = +A
        return self.value
    def __getattr__(self, name):
        return getattr(self.value, name)
    def __repr__(self):
        return '<Anaphor:%r>' % self.value

シームレスに、3-ARGオパートルも処理します pow() :-) :

>>> A = Anaphor()
>>> x = 1
>>> if x + 11 >> A:
...     print repr(A), A, +A, 'y' * A, 3.0 < A, pow(A, 2, 100)
...     
<Anaphor:12> 12 12 yyyyyyyyyyyy True 44
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top