我正在撰寫具有多個函式的代碼,其中大多數函式都包含相同的變數。我在下面提供了一些示例函式。
# First sample function
def cg2RollAxisHeight(z_frc, z_rrc, l_w, x_cg, z_cg):
theta = np.arctan((z_rrc-z_frc)/l_w)
z_axis = np.tan(theta)*l_w*x_cg
return z_cg-(z_axis z_frc)
# Second Sample function
def FrontLateralWT(W, l_w, t_f, K_phiF, K_phiR, A_Y, z_frc, z_rrc, x_cg, z_cg):
H = CG.cg2RollAxisHeight(z_frc, z_rrc, l_w, x_cg, z_cg)
b = l_w-(l_w*x_cg)
return A_Y*W/t_f*(H*K_phiF/(K_phiF K_phiR) b/l_w*z_frc)
我希望能夠在單個物件(例如字典)中定義所有變數和變數名稱,并能夠讓我的函式從該物件中提取所需的變數。
我嘗試以下列方式使用 **kwargs:
def cg2RollAxisHeight(**kwargs):
theta = np.arctan((z_rrc-z_frc)/l_w)
z_axis = np.tan(theta)*l_w*x_cg
return z_cg-(z_axis z_frc)
kwargs = {'W': 180, 'l_w': 2.4, 't_f': 1540, 'K_phiF': 78000, 'K_phiR': 46000,
'A_Y': 2.5, 'z_frc': 25, 'z_rrc': 60, 'x_cg': .6, 'z_cg': .4}
test = cg2RollAxisHeight(**kwargs)
print(test)
這里的問題是該函式無法將鍵識別為變數名。有沒有辦法在函式中使用字典鍵作為變數名?還是有更好的方法來做我所追求的?我想避免使用串列,因為該函式幾乎無法破譯。
def cg2RollAxisHeight(params):
theta = np.arctan((params[7]-params[6])/params[1])
z_axis = np.tan(theta)*params[1]*params[9]
return paramms[10]-(z_axis params[6])
params = [180, 2.4, 1540, 78000, 46000, 2.5, 25, 60, 0.6, 0.4}
test = cg2RollAxisHeight(params)
print(test)
雖然上述解決方案確實有效,但它不是一個簡潔的解決方案,我必須對許多其他更大的功能做同樣的事情。不理想!有沒有一種方法可以創建一個可以傳遞給多個函式的物件,而無需編輯函式的主體?
uj5u.com熱心網友回復:
這就是我使您的代碼作業的方式:
import numpy as np
zeDict = {'W': 180, 'l_w': 2.4, 't_f': 1540, 'K_phiF': 78000, 'K_phiR': 46000,
'A_Y': 2.5, 'z_frc': 25, 'z_rrc': 60, 'x_cg': .6, 'z_cg': .4}
def cg2RollAxisHeight(myDict):
theta = np.arctan((myDict['z_rrc']-myDict['z_frc'])/myDict['l_w'])
z_axis = np.tan(theta)*myDict['l_w']*myDict['x_cg']
return myDict['z_cg']-(z_axis myDict['z_frc'])
test = cg2RollAxisHeight(zeDict)
print(test)
在我看來,從長遠來看,您的方法可能會遭受不必要的復雜性。我建議使用類。
import numpy as np
class cg2:
def __init__(self):
# Please, initialize properly
self.W = 180
self.l_w = 2.4
self.t_f = 1540
self.K_phiF = 78000
self.K_phiR = 46000
self.A_Y = 2.5
self.z_frc = 25
self.z_rrc = 60
self.x_cg = .6
self.z_cg = .4
def RollAxisHeight(self):
theta = np.arctan((self.z_rrc-self.z_frc)/self.l_w)
z_axis = np.tan(theta)*self.l_w*self.x_cg
return self.z_cg-(z_axis self.z_frc)
def update(self):
# Code that updates your parameters goes here
pass
cg2obj = cg2()
test = cg2obj.RollAxisHeight()
print(test)
uj5u.com熱心網友回復:
嘗試 globals()[your_dictionary.keys[index_of_the_key]]
globals()[ ] 將 [ ] 中的字串作為變數名回傳
https://www.pythonpool.com/python-globals/#:~:text=Python% 20globals() function 是, global scope 實際上 包含。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429010.html
