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

2024-09-20 04:07:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: selfreturnifinitmaindefnotclass
2条回答

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

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

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

相关问题 更多 >