基于构造函数参数的类的条件访问 - python

from folder.test.test1 import Test1
from folder.test.test2 import Test2
from other_folder import Test3

class Sample(Test1, Test2, Test3):
    def __init__(self, version):
        Test3.__init__(self)

        if version == 'gen1':
            self.__class__ = Test1
            Test1.__init__()
        elif version == 'gen2':
            self.__class__ = Test2
            Test2.__init__()

    def login(self, ip):
        pass

if __name__ == '__main__':
    ob = Sample(version='gen2')
    ob.login('192.168.1.100')

我收到此错误:

AttributeError: 'Test2' object has no attribute 'login'

尽管我有一个login()类对象,但是无法访问类SampleSample方法。

我希望该对象可以访问SampleTest2Test3方法(而不是Test1,因为版本是'gen2')。如果版本是'gen1',则Sample对象应只能访问SampleTest1Test3方法,而不能访问Test2

参考方案

一种解决方案是将其分为2类(如果可以):

class BaseSample(Test3):
    def login(self, ip):
        pass

class SampleGen1(Test1, BaseSample):
    pass

class SampleGen2(Test2, BaseSample):
    pass

然后在您的代码中使用适当的类:

if version == 'gen1':
    ob = SampleGen1()
elif version == 'gen2':
    ob = SampleGen2()
ob.login('192.168.1.100')

那对你有用吗?

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

TypeError:'str'对象不支持项目分配,带有json文件的python - python

以下是我的代码import json with open('johns.json', 'r') as q: l = q.read() data = json.loads(l) data['john'] = '{}' data['john']['use…