に引数としてメソッド名を渡す:エラーまあ、私はこれを行うにしようとしていますクラスメソッド
class Foo(object):
def method1(self):
print "method1"
def method2(self):
print "method2"
class Fo1(object):
def __init__(self):
self.a = Foo()
def classMethod(self, selection):
self.a.selection()
A = Fo1()
A.classified('method2')
私はこのエラーを得た:
--> AttributeError: 'Fo1' object has no attribute 'selection'
私が使用したくありません
def classified(self,selection):
if selection == "method1": self.a.method1()
elif selection == "method2": self.a.method2()
私は渡すことができるように、私はメソッドをコーディングする必要がありますどのように:これは、(より多くのコーディング、私には思えます)引数としてのメソッド名? ありがとう!
'getattr(self.a、selection)()' –
実際にこれを行う理由はめったにありません。メソッドへの参照を直接渡すことができます: 'A.classMethod(Foo.method2)' – chepner
あなたは、classMethodを呼び出すことを意味するように分類されたクラスを呼び出します。つまり、classMethodを使用していて、交換可能に分類されています。名前を1つ選ぶ。 – dbliss