python - 在类方法中声明一个全局变量
问题描述
为了控制移液实验室机器人,我想创建一个可导入的模块,其中包含具有移液模式的类。为此,我定义了诸如 Sample、Reagents 之类的类,以便能够使用更具可读性的代码轻松访问和使用它们。
我的想法是让用户能够编写风格的字典:
Samples = {
'Sample1':{
'ID':'Sample1',
'volume' : 12,
'location' : sample_plate['A1'],
'concentration' : 166,
'fmol' : 147,
'nucleic_acid_type' : 0
},
'Sample2': {
'ID':'Sample2',
'volume' : 11,
'location': sample_plate['B1'], #location on the robotsdeck
'concentration' : 180,
'nucleic_acid_type' : 0,
'fmol':345 #molarity of the sample
}
}
那么这个 Dictionary 应该用于在 Jupyter Notebook 中定义与 Samples Name 同名的变量(例如 Sample1、Sample2)。
这些变量是类 Sample 及其方法的实例。
例如,要访问样本的体积并在整个移液工作流程中更轻松地跟踪它,我希望变量具有属性 .volume 来访问其体积,例如:
IN:
Sample1.volume
Out:
12
我定义了如下所示的类:
class Sample():
global Sample_Variable_Dict
Sample_Variable_Dict = {}
global Sample_List
Sample_List = []
def __init__(self, ID='ID_missing', volume = None, location= None , concentration= None, nucleic_acid_type= None, fmol= None):
self.ID = ID
self.volume = volume
self.location = location
self.concentration = concentration
__nucleic_acid_types = ['RNA','RNA-DNA Hybrid', 'ss-DNA', 'ds-DNA']
self.nucleic_acid_type = __nucleic_acid_types[nucleic_acid_type]
self.fmol = fmol
def Volume(self):
print(str(self.volume)+'µl')
def Concentration(self):
print(str(self.volume) +'ng/µl')
def FMOL(self):
print(str(self.fmol)+'fmol')
def Sample_Dicter(Sample_Dict):
for sample, data in Sample_Dict.items():
globals()[sample] = Sample(**data)
Sample_Variable_Dict[globals()[sample]] = []
for sample, data in Sample_Variable_Dict.items():
print(sample.ID)
return Sample_Variable_Dict
Sample_Dicter()
是一种应该能够使用样本字典作为输入的方法,然后在 Notebook 中创建样本的全局变量,并将它们全部组合在一起Sample_Variable_Dict
以使它们更容易迭代等。
在我用于测试类的笔记本中测试这些方法时,或者将方法复制到我的工作笔记本中时,它会按预期工作并在该笔记本中创建全局变量。
Sample_Dicter(Samples)
我的问题:为什么在我导入模块并使用 Samples 作为包含样本属性的字典调用之后,在工作的 Noebook 中没有创建(可访问)变量?
我使用导入方法
from Classes_Functions.class_Sample_Reagent import *
__init__.py
看起来像这样
__all__ = ['Classes']
可能的解决方法
我找到了解决问题的可能解决方法
for element, Liste in Sample_Variable_Dict.items():
print(element)
globals() [element.ID] = element
但我想知道一般问题:是否可以通过导入的类方法声明变量全局?
解决方案
推荐阅读
- sql - 使用周数和周天格式的日期范围的总值?
- amazon-web-services - Security group does not appear to belong to the same VPC as the input subnets
- javascript - ReactJS: replacing object from array with new value replaces whole array
- wordpress - WP pagination in rest api
- python - Given an array find element pairs whose sum is equal to the given sum and return the sum of their indices
- ruby - How to get commit history of users in gitlab in rails
- web-deployment - 我无法追踪浏览器显示的错误
- python - Gmail 发送的电子邮件提取
- java - 如何将通过spring-boot下拉列表获得的数据保存在数据库中?
- outlook-addin - 发送电子邮件后,ItemId 无效