首页 > 解决方案 > 将一个类文件中的变量调用到python3中的另一个文件

问题描述

嗨,我是 python 编程的新手。请帮我解决python3中的这个问题:

包.py

class one:

    def test(self):
        number = 100   ######I want to access this value and how?
        print('test')

class two:

    def sample(self):
        print('sample')

另一个.py

from pack import *

class three:

    def four(self):
        obj = one()
        print(obj.test())

###### I want to access the number value in this file and i don't know how #######

obj = three()
obj.four()

标签: pythonpython-3.x

解决方案


这是一个替代的 pack.py

class One:
    def __init__(self):
        self.number = 100

    def test(self):
        print('test')

class Two:
    def sample(self):
        print('Sample')

另一个.py

from pack import *

class Three:
    def four(self):
        self.obj = One().number
        return self.obj

three = Three().four()
print(three)

通过您的方法,您正在使用类来访问变量。最好在构造函数中实例化变量( 类One中的init方法)。然后导入该类并在另一个文件的另一个类中访问它。

此外,以大写字母开头的类命名也是一个好习惯。还有更多可能的方法,但希望它有所帮助。


推荐阅读