在python中,如何用不同的名称将不同的方法封装在一个类中?

2024-10-01 11:41:38 发布

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

因此,我目前正在尝试用Python开发一个测试框架,并且我已经开发了一系列API方法用于此。这个框架将被许多对“测试中的系统”有不同经验和知识的不同的人使用,因此决定同时提供一个简单的API和一个更“本地”的API是有用的。 API方法都是使用ip会话与“被测系统”进行接口,并且在整个测试会话期间,该会话必须是相同的。到现在为止,一直都还不错。不过,我发现在同一个测试中同时使用“简单API方法”和“本机API方法”可能很有用,而且它们必须以某种方式共享这个ip会话。在这之前我做了这样的东西:

nativeAPI(object):
    def __init__(self):
        self.session = createSession(password, systemip)

    def someAPImethod(self):
        return dosomeTestStuff(self.session)

simpleAPI(object):
    def __init__(self):
        self.session = createSession(password, systemip)

    def someAPImethod(self):
        return dosomeTestStuff(self.session)


#Test code written by a person using the framework could look something like this.
testMethods = nativeAPI()
testMethods.someAPImethod()

但现在我更希望“测试员”可以使用类似的语法:

testMethods = createSession()
testMethods.nativeAPI.someAPIMethod()

我试图在“createSession”类中使用“NativeAPI”类来实现这一点,但最终遇到了一些问题,比如:“必须以实例作为第一个参数来调用unbound方法”。所以我问你:我该怎么处理?在Python中什么是好的设计模式?你知道吗


Tags: 方法selfip框架apiobjectinitsession
2条回答

只需在createSession中创建一个包含简单nativeAPI实例的简单对象,并返回:

class Wrapper(object):

    def __init__(self, nativeAPI):
        self.nativeAPI = nativeAPI

def createSession():
    nativeAPI = ...
    return Wrapper(nativeAPI)

我将使simpleAPI成为nativeAPI的子类。你知道吗

这样,即使有simpleAPI实例,也可以始终使用nativeAPI方法。更好的是,simpleAPI方法可以根据nativeAPI实现,从而简化代码:

nativeAPI(object):
    def __init__(self):
        self.session = createSession(password, systemip)

    def someAPImethod(self):
        return dosomeTestStuff(self.session)

simpleAPI(nativeAPI):
    def someSimpleAPImethod(self):
        result = self.someAPImethod()
        result.doSomethingToSimplify()
        return result

相关问题 更多 >