【发布时间】:2020-03-18 00:26:42
【问题描述】:
我有 2 个模块,第一个模块的类 One 带有一个返回值的函数。第二个有 2 个类 Two 和 Three 功能。我已将第一个模块中的类导入到第二个模块中。
在Two 类的函数i 中,我已将x 类从One 分配给y。从那里我可以通过打印y 访问返回值,该函数还返回程序中其他地方需要的变量type。
但还需要从类 Three 中的函数 z 中访问同一个变量 y。
我在Three 类中使用的方法返回错误。我试过使用getattr,但没有发现任何乐趣。但我相信我可能用错了。
我唯一的其他解决方案是返回 y 和 type。然后将Two类中的函数i分配给Three类的函数z中的pop。但这会从 x 类 One 中调用函数,这意味着我必须输入另一个值,然后它会打印多条不需要的行。
我已经创建了这个问题的模拟来尝试找到解决方案,但我有点卡住了。我需要在许多其他类中多次访问类Two 的函数i 中的y 的值。
方法一:
模块 1:TestOne.py
class One():
def x(self):
Go = input("Please enter value\n")
return Go
模块 2:Test.py
from TestOne import*
class Two():
def i(self):
type = "Move"
y = One.x(self)
print("Test 1: ",y)
return type
class Three():
def z(self):
print("Test 2: ", Two.i.y)
模块 3:TestMain.py
from Test import*
p = Two()
t =Three()
p.i()
t.z()
错误:
PS C:\Users\3com\Python> python testmain.py
Please enter value
Test 1:
Traceback (most recent call last):
File "testmain.py", line 9, in <module>
t.z()
File "C:\Users\3com\Python\Test.py", line 16, in z
print("Test 2: ", Two.i.y)
AttributeError: 'function' object has no attribute 'y'
方法二:
模块 1:TestOne.py
class One():
def x(self):
Go = input("Please enter value\n")
return Go
模块 2:Test.py
from TestOne import*
class Two():
def i(self):
type = "Move"
y = One.x(self)
print("Test 1: ",y)
return type, y
class Three():
def z(self):
pop = Two.i(self)[1]
print("Test 2: ", pop)
模块 3:TestMain.py:
from Test import*
p = Two()
t =Three()
p.i()
t.z()
输出:
PS C:\Users\3com\Python> python testmain.py
Please enter value
1
Test 1: 1
Please enter value
1
Test 1: 1
Test 2: 1
编辑:
我做了一些挖掘,并有一个解决问题的解决方案。使用global。但是发现很多文章说global使用不当会有些危险,
方法 3:工作解决方案。满足所需的输出。
模块 1:TestOne.py
class One():
def x(self):
Go = input("Please enter value\n")
return Go
模块 2:Test.py
from TestOne import*
class Two():
def i(self):
type = "Move"
global y
y = One.x(self)
print("Test 1: ",y)
return type
class Three():
def z(self):
print("Test 2: ", y)
模块 3:TestMain.py:
from Test import*
p = Two()
t =Three()
p.i()
t.z()
输出:(期望的输出)
PS C:\Users\3com\Python> python testmain.py
Please enter value
1
Test 1: 1
Test 2: 1
【问题讨论】:
标签: function class get attributes var