如何从python中另一个文件中的函数访问变量 [英] How to access a variable from a function which is in another file in python

查看:43
本文介绍了如何从python中另一个文件中的函数访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.作为我项目的一部分,我正在使用 python2.7.我正在处理 python 中的多个文件.在这里,我面临一个问题,即从另一个文件中使用特定函数的变量,该文件已导入到当前文件中.请帮助我实现这一目标.

I am new to python. As part of my project, I am working with python2.7. I am dealing with multiple files in python. Here I am facing a problem to use a variable of particular function from another file which was I already imported in my current file. Please help me to achieve this.

file1.py
class connect():
    # Contains different definitions
    def output():
        a = "Hello"
        data = // some operations
        return data

file2.py
from file1 import *
# Here I need to access both 'a' and 'data' variable from output()

推荐答案

所以自从我开始写关于约定的文章以来,你已经编辑了很多,所以我又重新开始了.

So you have edited it quite a bit since I started writing about conventions so I have started again.

首先,你的return语句没有缩进,应该在输出方法中缩进.

First, your return statement is out of indentation, it should be indented into the output method.

def output():
    a = "Hello"
    data = // some operations
    return data

其次,Python 中关于类名的约定是 CamelCase,这意味着您的类应该被称为Connect".当你的类没有继承任何东西时,也不需要添加圆括号.

Second, the convention in Python regarding class names is CamelCase, which means your class should be called "Connect". There is also no need to add the round brackets when your class doesn't inherit anything.

第三,现在你只能使用数据",因为只返回数据.您可以做的是通过将 return 语句替换为以下内容来同时返回 a 和 data:

Third, right now you can only use "data" since only data is returned. What you can do is return both a and data by replacing your return statement to this:

return a, data

然后在你的第二个文件中,你所要做的就是写 a_received, data_received = connect.output()

Then in your second file, all you have to do is write a_received, data_received = connect.output()

完整代码示例:

file1.py

class Connect:

    def output():
        a = "Hello"
        data = "abc"
        return a, data

file2.py

from file1 import Connect

a_received, data_received = Connect.output()

# Print results
print(a_received)
print(data_received)

第四,还有其他方法可以解决这个问题,比如创建实例变量,然后就不需要返回了.

Fourth, there are other ways to combat this, like create instance variables for example and then there is no need for return.

file1.py

class Connect:

    def output(self):
        self.a = "Hello"
        self.data = "abc"

file2.py

from file1 import Connect

connection = Connect()
connection.output()

print(connection.a)
print(connection.data)

还有类变量版本.

file1.py

class Connect:

    def output():
        Connect.a = "Hello"
        Connect.data = "abc"

file2.py

from file1 import Connect

Connect.output()

print(Connect.a)
print(Connect.data)

最终,正确"的方法取决于用途.

Eventually, the "right" way to do it depends on the use.

这篇关于如何从python中另一个文件中的函数访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆