导入模块、函数、实例

2024-09-27 02:14:39 发布

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

我一直在运行一些测试来了解导入的工作原理:

文件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


Tags: 文件实例代码importselfinitdefclass
2条回答

回答您的问题“我想知道是否有一种方法可以修改下面的代码来直接导入我需要的实例”:没有

正如您无法进入函数并在模块中获取其内部工作一样,您也不能在导入中这样做

这个函数定义了什么是Player,实例化了它,并调用了它的一个属性。然后函数结束,程序不知道什么是Player,更不知道什么是zim,它的hp属性是什么

在你的test1中你有:

class Player():
    hp=0
    def __init__(self):
        self.hp=0
    zim = Player()
    zim.hp = 5

这将抛出一个NameError: name 'Player' is not defined,因为您正在创建一个Player的实例,而它的类定义还没有结束。我想你打算做:

class Player():
    hp=0
    def __init__(self):
        self.hp=0
zim = Player()    # This and the next line are indented differently
zim.hp = 5

在这种情况下,zim成为test1的模块变量,因此zim.hp可以从test2打印

现在,将test1编辑为:

def Test():
    class Player():
        hp=0

        def __init__(self):
            self.hp=0

    zim = Player()
    zim.hp = 5

Player对象实例化在它的类声明之外,所以它是正确的。但是变量zim只存在于函数Test()中。从另一个模块打印zim.hp时,zim不作为要从test2访问的模块变量存在

可能您可以从Test()方法return zim.hp。如果这样做,就可以从test2访问值,作为print(test1.Test())

希望这有帮助

相关问题 更多 >

    热门问题