python中如何处理不同函数/类中大量变量的访问
我现在想要改进的代码如下所示,python中如何处理不同函数/类中大量变量的访问,python,variables,Python,Variables,我现在想要改进的代码如下所示, 哪个f0和f1(或2个以上的函数)需要相同的变量。 我必须编写大约50行代码来描述每个函数的变量设置。 我怎样才能做得更像蟒蛇 --f0.py --f1.py --根斯特里 from f0 import * from f1 import * f = open('xxx.x','w') f.write(f0.gen(1)+f1.gen(1)) f.close() from f0 import * from f1 import * f = open('xxx.x
哪个f0和f1(或2个以上的函数)需要相同的变量。
我必须编写大约50行代码来描述每个函数的变量设置。 我怎样才能做得更像蟒蛇 --f0.py --f1.py --根斯特里
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
(我真的不知道如何使用class,但我发现这可以解决我的问题
请描述一下,也许这有助于理解我的问题)
我尝试用类来实现,这样我就可以通过继承conf进行访问。
我知道我可以通过“self.a”访问,但是有什么方法可以直接在函数中使用“a”吗 --conf.py
class conf:
def __init__(self, csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
self.a = 1
self.b = 2
...
--f0.py
--f1.py
--根斯特里
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
代码有点混乱,我不确定您到底在尝试什么,但这里有一些一般帮助 此代码:
for row in csv.DictReader(open(csv_f)):
c += row['x']
将把columnx
的内容附加到c
import conf
class f0(conf):
def __init__(self, csv_f):
super(f0,self).__init__(self) # Fixed
self.csv_f = csv_f
def gen(self):
# var set
c = self.c #
a = self.a
b = self.b
# do sth in f0
xx = a + b
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0(filename).gen()+f1(filename).gen())
f.close()
您可以在任何需要c
的地方使用self.c
而不是c=self.c
import conf
class f0(conf):
def __init__(self, csv_f):
super(f0,self).__init__(self) # Fixed
self.csv_f = csv_f
def gen(self):
# var set
c = self.c #
a = self.a
b = self.b
# do sth in f0
xx = a + b
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0(filename).gen()+f1(filename).gen())
f.close()
您的前两个功能在以下几行中有所不同:
xx = a + b
vs
您可以将此作为附加参数传入
def gen(csv_f, f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# use the passed function
xx = f(a, b)
...
return str
l0 = lambda a, b: a + b
l1 = lambda a, b: a * b + b
# call gen with one of these lambdas as the second argument
gen(1, l0)
gen(1, l1)
def gen(csv_f, f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# use the passed function
xx = f(a, b)
...
return str
l0 = lambda a, b: a + b
l1 = lambda a, b: a * b + b
# call gen with one of these lambdas as the second argument
gen(1, l0)
gen(1, l1)