2014-11-06 53 views
0
class A: 
    def __init__(self,opt): 
     if not hasattr(self,opt): 
      raise SystemExit(1) 
     getattr(self,opt)() 

    def optionA(self): 
     return "A" 

    def optionB(self): 
     return "B" 

現在,當我嘗試使用它一個類根據選項返回不同方法的模式?

>> A('optionA') 
<__main__.A instance at 0x7f87bccfca70> 

我想它返回的是 「A」。所以,我嘗試使用

class A: 
    def __call__(self,opt): 
     if not hasattr(self,opt): 
      raise SystemExit(1) 
     getattr(self,opt)() 

    def optionA(self): 
     return "A" 

    def optionB(self): 
     return "B" 

這工作,但現在我不得不做出這個醜陋的通話

A()("optionA") 
+1

任何類的'__init__'方法都不會返回一個值,並且它的任何返回值都會被丟棄。 – 2014-11-06 08:20:50

+0

如果要在類實例化中返回「A」,您將如何將實例賦值給變量? – 2014-11-06 08:23:32

+1

不確定要真正理解你的問題,但特殊方法'__new__'返回一個對象,而不是像'__init__'那樣配置一個剛創建的對象。 – 2014-11-06 09:28:21

回答

1

你想用這個來解決什麼問題 - :另一種方法isntance getdata(在我的情況)?你只是將該類用作函數容器?你可以嘗試下面的內容;它有點漂亮。

class A: 
    @staticmethod 
    def optionA(): 
     return "A" 

    @staticmethod 
    def optionB(): 
     return "B" 

    @staticmethod 
    def run(opt): 
     if not hasattr(A, opt): 
      raise SystemExit(1) 
     else: 
      f = getattr(A, opt) 
      return f() 

print A.run('optionA') 
1

init方法不返回一個值,如果要使其工作做到這一點, 使用

class A: 
    def __init__(self,opt): 
     self.opt = opt   # initialize the argument 
     if not hasattr(self,opt): 
      raise SystemExit(1) 
    def getdata(self): 
     return getattr(self, self.opt)() #`self.opt` use the argument 

    def optionA(self): 
     return "A" 

    def optionB(self): 
     return "B" 
a = A('optionA') 
c = a.getdata() 
print c 
相關問題