一个类的模式,根据选项返回不同的方法?

时间:2014-11-06 08:10:15

标签: python oop

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")

2 个答案:

答案 0 :(得分:1)

init方法没有返回值,如果你想让它工作,请执行此操作, 使用另一种isntance方法getdata(在我的例子中): -

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

答案 1 :(得分:1)

你想用这个解决什么问题?您是否只是将该类用作函数容器?你可以试试下面的;它有点漂亮。

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')