在Python OOP中声明全局变量并跨方法传递值
声明全局变量并跨方法传递值 在Python OOP中 因此,我想将nethod1的结果传递给 方法2 比如说在Python OOP中声明全局变量并跨方法传递值,python,oop,Python,Oop,声明全局变量并跨方法传递值 在Python OOP中 因此,我想将nethod1的结果传递给 方法2 比如说 import pandas as pd class ExampleClass(object): def method1(self): file_path="/some/path/" file_data="populaion_data.csv" data=pd.read_csv(file_path+file_data) res = data.head(5)
import pandas as pd
class ExampleClass(object):
def method1(self):
file_path="/some/path/"
file_data="populaion_data.csv"
data=pd.read_csv(file_path+file_data)
res = data.head(5)
def method2(self):
"""
In his method, i would like to do the following tasks
(1)read the "res" from the method1.
(2)want to get the value of "file_path" from method1 again.
"""
而且,我认为最好是宣布
“file_path”值作为全局变量,因此我可以使用它
跨多个方法的值。如果希望在同一类中的多个方法之间可以访问该变量,则只需声明一个实例变量:
import pandas as pd
class ExampleClass(object):
def __init__(self):
self.file_path = "/some/path/"
self.res = ''
def method1(self):
file_data="populaion_data.csv"
data=pd.read_csv(self.file_path+file_data)
self.res = data.head(5)
def method2(self):
"""
In his method, i would like to do the following tasks
(1)read the "res" from the method1.
(2)want to get the value of "file_path" from method1 again.
"""
#self.file_path and self.res will be accessible here too.
print (self.file_path, self.res)
a = ExampleClass()
a.method2()
您可以执行以下操作:
def method1(self):
self.file_path = "some/path/"
file_data = "population_data.csv"
data=pd.read_csv(file_path+file_data)
self.res = data.head(5)
def method2(self):
print(self.file_path, self.res)
请注意,您必须在method1之后调用method2。您也可以从method2
调用method1
,然后使用如下值:
def method1(self):
file_path = "some/path/"
file_data = "population_data.csv"
data=pd.read_csv(file_path+file_data)
res = data.head(5)
return (file_path, res)
def method2(self):
file_path, res = self.method1()
还可以将其定义为类变量或静态变量。
要将其定义为静态变量,只需执行以下操作:
class ExampleClass:
file_path = "some/path"
data=pd.read_csv(file_path+file_data)
res = data.head(5)
def method2(self):
print(self.file_path, self.res)
这不是一个面向对象的问题。使用OOP,您可以操作由类定义的对象,从基本角度来看,这些类是类型。类型是具有状态(数据)和行为(称为方法的集成函数)的组件。因此,OOP中没有全局变量。数据可以通过方法参数提供给对象,处理结果应该由方法返回 在这个cas中,我不明白为什么这些函数在类中,除非您需要前面答案中定义的对象。根据您的代码示例,这是通过函数解决的,对于这些函数,数据应作为参数传递:
import pandas as pd
DEFAULT_FILE_PATH ="/some/path/"
def method1(filename, file_path='/'):
data=pd.read_csv(file_path + file_data)
return data.head(5)
def method2(data, file_path='/'):
"""
In his method, i would like to do the following tasks
(1)read the "res" from the method1.
(2)want to get the value of "file_path" from method1 again.
"""
因此,您知道什么是文件路径
,可以将其用作
method2(method1("populaion_data.csv", DEFAULT_FILE_PATH), DEFAULT_FILE_PATH)
不,类的全部目的是避免全局状态。使用实例变量。另外,如果您正在运行python3.x,则不需要
类ExampleClass(object):
。只需使用类示例class:
@juanpa.arrivillaga是的,你是对的。找到解决办法了。谢谢,我不知道它不见了。将其添加到代码中。谢谢@我想这就是我一直在寻找的答案。非常感谢您的时间和努力。您的建议很有帮助,但是,这只是一个可能的长程序的开始,我相信我以后会使用一些类继承,因此希望将所有函数/方法保留在一个类中,以便我以后可以使用它们。感谢您的时间。您的代码示例对我接下来的步骤很有帮助。你的回答比我原来的问题更进一步。非常感谢你。