0

呼び出し可能なクラスを別のクラスの関数として割り当て、所有する関数から所有者クラスを参照したい:

class DoIt(object):

    def __call__(self):
        print "%s did it" % self.name

class Doer(object):

    def __init__(self, name):
        self.name = name

    doSomething = DoIt()


doer = Doer("Bob")
doer.doSomething()

上記のコードでは、doSomething()「Bob did it」を出力する関数が必要ですが、このコードでは

AttributeError: 'DoIt' オブジェクトに属性 'name' がありません

self は Doer インスタンスではなく DoIt インスタンスを参照するためです。Doer インスタンスを参照することは可能ですか?

4

3 に答える 3

4
class DoIt(object):

    def __get__(self, instance, owner):
        def done():
            print "%s did it" % instance.name
        return done

class Doer(object):

    def __init__(self, name):
        self.name = name

    doSomething = DoIt()


doer = Doer("Bob")
doer.doSomething()

説明:( これは、この答えをできる限り説明する質問者です)

Pythonは、(インスタンス変数またはプロパティとしての属性とは対照的に)属性として機能するクラスである記述子クラスを提供します。記述子クラスの__get__メソッドは、そのクラスが別のクラスの属性として割り当てられ、アクセスされたときに返されるものを指示します。また__get__、所有するインスタンスと所有するクラスの両方にアクセスできます(メソッドのシグネチャを参照)。

関数を__get__返すことにより、基本的に、その所有者にアクセスできる呼び出し可能オブジェクトを作成します。

記述子の詳細については、「属性、プロパティ、記述子-Pythonでのスキルの構築」を参照してください。

于 2012-05-02T20:47:37.277 に答える
2

これを実現する 1 つの方法を次に示します。

class DoIt(object):
    def __init__(self, obj):
        self.obj = obj

    def __call__(self):
        print "%s did it" % self.obj.name

class Doer(object):
    def __init__(self, name):
        self.name = name
        self.doSomething = DoIt(self)

doer = Doer("Bob")
doer.doSomething()    # prints 'Bob did it'
于 2012-05-02T20:32:03.507 に答える
0

これは、Ignacioの答えの純粋に別の例です。「呼び出し可能」にパラメーターが必要な場合に同じ概念を示したかったのです。

class DoIt(object):

    def __get__(self, instance, owner):

        def done(what):
            print "%s did something %s" % (instance.name, what)
        return done

class Doer(object):

    def __init__(self, name):
        self.name = name
    doSomething = DoIt()

doer = Doer("Bob")
doer.doSomething("cool")

プリント:

ボブは何かクールなことをしました

于 2012-05-03T12:20:41.693 に答える