提问人:mac 提问时间:8/1/2023 最后编辑:mac 更新时间:8/1/2023 访问量:38
在Python中首次定义类时如何获取变量数据?
how to get a variable data when class is first defined in python?
问:
我有 2 个 python 脚本,我尝试从其中一个 python 脚本访问变量,并在类定义或初始化期间在另一个 python 脚本中使用它。
例如,这里有 2 个脚本
script1.py
dname = None
class Invenger(BBCAPIInfra):
def __init__(self,
server_ip):
def get_dname_from_bed(self, dip):
global dname
dname = dip.foo.bar
return dname
这是我想使用 dname 值的第二个脚本
script2.py
from foo.bar.abc.script1 import dname
class LAUtils(BBCAPIInfra):
yml_path = dname
我还有 1 个脚本,实际上是我从命令行触发的,它看起来像这样
#script3.py
from script1 import Invenger
class CommonSetup(commonsetup):
def common_setup:
test.params['inv'] = Invenger(server_ip=self.server_ip)
def get_dname:
inv.get_dname_from_bed(dip)
print(dname)
在这里,当我执行脚本时,我得到哪个是正确的,但是我怎样才能更改脚本以获得 script2 中的实际值?yml_path =None
dname
答:
1赞
Shailesh Saravanan
8/1/2023
#1
要共享 between 和 的值,您可以创建一个单独的模块来存储共享变量,然后将其导入到两个脚本中。以下是修改脚本的方法:dname
script1.py
script2.py
- 创建一个新模块来存储共享变量:
shared.py
dname
# shared.py
dname = None
- 修改以使用该模块:
script1.py
shared.py
# script1.py
from shared import dname
class Invenger(BBCAPIInfra):
def __init__(self, server_ip):
...
def get_dname_from_bed(self, dip):
global dname
dname = dip.foo.bar
return dname
- 修改以使用该模块:
script2.py
shared.py
# script2.py
from shared import dname
class LAUtils(BBCAPIInfra):
yml_path = dname
- 修改以将值传递给,然后从以下位置访问更新后的值:
script3.py
dip
Invenger
dname
shared.py
# script3.py
from script1 import Invenger
from shared import dname
class CommonSetup(commonsetup):
def common_setup(self):
inv = Invenger(server_ip=self.server_ip)
dip = ... # Define the value of dip here
inv.get_dname_from_bed(dip)
print(dname)
现在,当您运行 时,它应该正确地更新 中的变量 through 并使用 中的更新值。确保为 in 定义适当的值以正确更新 。script3.py
dname
shared.py
script1.py
script2.py
dip
script3.py
dname
评论
0赞
quamrana
8/1/2023
这不可能奏效。该行仅影响该模块中的全局。dname = dip.foo.bar
评论