我应该如何在不同的类中共享一个变量?

2024-03-29 12:16:18 发布

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


Tags: python
3条回答

我最终使用了this from stackoverflow这是可行的。 基本上,将我的共享变量myVar1myVar2放入一个新文件myfile.py,然后import myfile放入runTests.py,并给变量赋值如下:

myfile.myVar1 = sys.argv[1]

在其他需要使用myVar1import myfile的文件中,使用如下变量:

myfile.myVar1
import sys
params = sys.argv

你知道吗系统argv我会给你一张单子

$ python myproram.py var1 var2 var3

你知道吗系统argv[0]=>;我的程序.py你知道吗

你知道吗系统argv[1] =>变量1

你知道吗系统argv[2] =>变量2

等等

您可以在任何类中访问它

from os import sys


class addc:
    def __init__(self , no1 , no2):
        self.no1 = no1
        self.no2 = no2
    def addition(self):
        total = self.no1 + self.no2
        return total



if len (sys.argv) !=3:
    print "no u cant go forwrd"
    print "agument is less"
    sys.exit()

obj_initial = addc(2 , 3 ) 
ans1 = obj_initial.addition() 
print " the total of internla argumnet is %i"%ans1

cmnd_argu1 = int(sys.argv[1]) 
cmnd_argv2 = int (sys.argv[2])

obj_cmnd_argu = addc(cmnd_argu1 , cmnd_argv2)
ans2_cmnd_argu = obj_cmnd_argu.addition()
print " the total of internla argumnet is %i" % int(ans2_cmnd_argu)

相关问题 更多 >