簡體   English   中英

在類方法中將方法名稱作為參數傳遞時出錯

[英]Error passing a method name as argument in a class method

好吧,我正在嘗試這樣做:

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來執行此操作,例如

def classMethod(self, selection):
    getattr(self.a, selection)()

getattr為對象獲取一個屬性名稱,然后返回該屬性,然后可以調用該屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM