我正在为粒子物理学项目编写代码(使用pyroot)。
在我的初稿中,我使用以下行
for i in MyTree:
pion.SetXYZM(K_plus_PX, K_plus_PY, K_plus_PZ,K_plus_MM)
这基本上为π介子赋予括号中变量的值,即momenta和inv。大量的kaon。
除了物理学,我想写一个"形式的函数":
def myfunc(particle):
return %s_PX % particle
我知道这是错的。我想要实现的是编写一个函数,允许对于给定的粒子,将particle_PX,particle_PY等设置为SetXYZM的参数。
感谢您的帮助,
B
答案 0 :(得分:1)
要从字符串变量访问类属性,可以使用python的getattr
:
import ROOT
inputfile = ROOT.TFile.Open("somefile.root","read")
inputtree = inputfile.Get("NameOfTTree")
inputtree.Print()
# observe that there are branches
# K_plus_PX
# K_plus_PY
# K_plus_PZ
# K_plus_MM
# K_minus_PX
# K_minus_PY
# K_minus_PZ
# K_minus_MM
# pi_minus_PX
# pi_minus_PY
# pi_minus_PZ
# pi_minus_MM
def getx(ttree,particlename):
return getattr(ttree,particlename+"_PX")
def gety(ttree,particlename):
return getattr(ttree,particlename+"_PY")
def getz(ttree,particlename):
return getattr(ttree,particlename+"_PZ")
def getm(ttree,particlename):
return getattr(ttree,particlename+"_MM")
def getallfour(ttree,particlename):
x = getattr(ttree,particlename+"_PX")
y = getattr(ttree,particlename+"_PY")
z = getattr(ttree,particlename+"_PZ")
m = getattr(ttree,particlename+"_MM")
return x,y,z,m
for entry in xrange(inputtree.GetEntries()):
inputtree.GetEntry(entry)
pion1 = ROOT.TLorentzVector()
x = getx(inputtree,"K_plus")
y = gety(inputtree,"K_plus")
z = getz(inputtree,"K_plus")
m = getm(inputtree,"K_plus")
pion2.SetXYZM(x,y,z,m)
x,y,z,m = getallfour(inputtree,"pi_minus")
pion2 = ROOT.TLorentzVector()
pion2.SetXYZM(x,y,z,m)
由Josh Caswell链接,您可以类似地访问变量名称:
def getx(particlename):
x = globals()[partilcename+"_PX"]
尽管这可能会很快变得很糟糕,无论你的变量是全局的还是本地的,还是本地的,在哪种情况下。