2014-11-06 52 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 
相关问题