我正在寻找一种方法来根据创建对象时作为参数传递的条件返回类对象。
myclass1.py
class myver1():
def __init__(self):
print("I am in myver1")
def fun1(self):
print("I am in method func1 - myver1")
def fun2(self):
print("Access this method if version 1 is passed - myver1")
class myver2():
def __init__(self):
print("I am in myver2")
def fun1(self):
print("I am in method func1 - myvers2")
def fun2(self):
print("Access this method if version 2 is passed - myver2")
myclass2.py
class libtest():
def __init__(self, version):
self.version = version
self.ret_obj
def ret_obj(self):
if self.version == 1:
return myver1()
if self.version == 2:
return myver2()
testobj = libtest(version=1)
testobj.fun1()
预期输出:
I am in method func1 - myver1
运行时看到的错误:
Traceback (most recent call last):
File "C:\test44.py", line 12, in <module>
mytest.myver1()
AttributeError: 'libtest' object has no attribute 'myver1'
已编辑::谢谢大家,我已按照建议调用了该对象:
mytest = libtest(version=2).ret_obj()
mytest.fun1()
这是一个正确的方法吗?有没有更好的方法?