在python3中将一个类文件中的变量调用到另一个文件

2024-03-28 13:11:56 发布

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

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

pack.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')

另一个

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()


Tags: andtotestselfobjnumberaccessvalue
2条回答

number需要在全局范围内,这意味着在函数定义之外(不应该缩进)

如果变量在函数中,则无法在另一个文件中获取它

pack.py

number = 100
def test():
   test.other_number = 999 # here we assigne a variable to the function object.
   print("test")

另一个

import pack

pack.test()
print(pack.number)

print(test.other_number) # this only works if the function has been called once

或者,如果您正在使用类:

pack.py

class Someclass():
    other_number = 999 # here we define a class variable

    def __init__(self):
        self.number = 100 # here we set the number to be saved in the class

    def test(self):
        print(self.number) # here we print the number

另一个

import pack

somclass_instance = pack.Someclass() # we make a new instance of the class. this runs the code in __init__
somclass_instance.test() # here we call the test method of Someclass
print(somclass_instance.number) # and here we get the number

print(Someclass.other_number) # here we retrieve the class variable

这里有一个替代方案 pack.py

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

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

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

另一个

from pack import *

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

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

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

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

相关问题 更多 >