我一直在运行一些测试来了解导入的工作原理:
文件1:
class Player():
hp=0
def __init__(self):
self.hp=0
zim = Player()
zim.hp = 5
文件2:
import test1
print(test1.zim.hp)
我运行file2:并得到一个5的输出
所以,我把文件1改成:
def Test():
class Player():
hp=0
def __init__(self):
self.hp=0
zim = Player()
zim.hp = 5
我一直试图修改file2中的代码,以获得5的输出,但失败了。有没有办法先导入函数,然后导入实例特定的数据(本例中是hp)?我知道“return”,但是想知道是否有方法修改下面的代码来直接导入我需要的实例
ie:abc会是。。。。???O.O
import test1
print(abc.test1.zim.hp)
~T
回答您的问题“我想知道是否有一种方法可以修改下面的代码来直接导入我需要的实例”:没有
正如您无法进入函数并在模块中获取其内部工作一样,您也不能在导入中这样做
这个函数定义了什么是
Player
,实例化了它,并调用了它的一个属性。然后函数结束,程序不知道什么是Player
,更不知道什么是zim
,它的hp
属性是什么在你的
test1
中你有:这将抛出一个
NameError: name 'Player' is not defined
,因为您正在创建一个Player
的实例,而它的类定义还没有结束。我想你打算做:在这种情况下,
zim
成为test1
的模块变量,因此zim.hp
可以从test2
打印现在,将
test1
编辑为:Player
对象实例化在它的类声明之外,所以它是正确的。但是变量zim
只存在于函数Test()
中。从另一个模块打印zim.hp
时,zim
不作为要从test2
访问的模块变量存在可能您可以从
Test()
方法return zim.hp
。如果这样做,就可以从test2
访问值,作为print(test1.Test())
希望这有帮助
相关问题 更多 >
编程相关推荐