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

时间:2020-02-04 12:46:21

标签: python python-3.x

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

pack.py

class Solution {
    public String reverseWords(String s) {
        String[] arr1=s.split(" ");
        String reverseWorlds="";
        for(int i=0;i<=arr1.length-1;i++) {
            String reverseString="";
            for(int j=arr1[i].length()-1;j>=0;j--) {
                char ch=arr1[i].charAt(j);
                reverseString=reverseString+ch;
            }
            if(i==0) {
                reverseWorlds+=reverseString;
            }else {
                reverseWorlds+=" "+reverseString;
            }
        }
        return reverseWorlds;
    }
}

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

2 个答案:

答案 0 :(得分:0)

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

如果变量在函数内部,则不可能在另一个文件中获取它

pack.py

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

another.py

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

another.py

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

答案 1 :(得分:0)

这是另一种选择 pack.py

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

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

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

another.py

from pack import *

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

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

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

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