我有一个变量名列表检查.getargspec(函数).args。每个列表项都是一个变量名的字符串。我需要从函数内部使用这些字符串名称,以便检查参数变量的值是否为字符串。在
这就是我的工作
@staticmethod
def boyleslaw(p, V, k):
"""pV = k
p=pressure Pa, V=volume m^3, k=constant
substitute letter to solve for that value
return x"""
#sv = countvar(gasses.boyleslaw)
sv = 0
if p == 'p': sv += 1
if V == 'V': sv += 1
if k == 'k': sv += 1
if sv > 1:
raise ValueError('Too Many Variables')
if p == 'p' and sv == 1:
x = k/V
return x
elif V == 'V' and sv == 1:
x = k/p
return x
elif k == 'k' and sv == 1:
x = p*V
return x
@staticmethod
def charleslaw(V, T, k):
"""V/T = k
V=volume m^3, T=temperature K, k=constant
substitute letter for value to solve for
return x"""
#sv = countvar(gasses.charleslaw)
sv = 0
if V == 'V': sv += 1
if T == 'T': sv += 1
if k == 'k': sv += 1
if sv > 1:
raise ValueError('Too Many Variables')
if V == 'V' and sv == 1:
x = k*T
return x
elif T == 'T' and sv == 1:
x = V*k
return x
elif k == 'k' and sv == 1:
x = V/T
return x
我想结束这个过程
^{pr2}$在它自己的count variables函数中对参数进行计数,并检查每个参数值是否为字符串。到目前为止我要做的…然后墙+头。。。在
@staticmethod
def countvar(module):
"""Count number of Variables in args"""
vc = 0
alist = inspect.getargspec(module)
for i in alist.args:
if isinstance(i, str) == True:
vc += 1
return vc
无论函数的值是多少,它都返回3,因为列表.args是一个字符串。我只想在每个变量的值都是字符串的情况下递增计数器,如果有多个变量,则会引发ValueError。如何将字符串“p”转换为变量p。。。在
编辑:澄清
boyleslaw(6886019.02, 1, k) #Solve for k
inspect.getargspec(boyleslaw).args
返回['p', 'V', 'k']
我要一份清单[6886019.02, 1, 'k']
alist[0]
=
返回'p'
\string name
我需要return p
变量值
如果值p是一个字符串(如果在调用时选择了一个变量来求解),则递增计数器用于错误处理
boyleslaw(6886019.02, 1, k)
不引发错误
boyleslaw(6886019.02, V, k)
会raise ValueError('Too Many Variables')
以下是另一种解决方案:
假设这三个量的第一个函数。然后返回第三个数量。所以你不必明确告诉这个函数要解哪个量,因为从给定的量来看,这是显而易见的。在
^{pr2}$使用位置参数定义函数时,每个参数都将成为必需的:
因此,不需要检查是否传递了每个参数,因为Python将为您处理这些问题。在
第二部分,你不清楚你想要什么。首先,检查变量的名称是否与传递的值
^{pr2}$if V == 'V'
匹配,然后对其应用一个公式,该公式不会按您的想法操作,因为不能将两个字符串相乘。在所以我认为你真正想要的是尝试用数字进行计算,如果失败了,就提出一个适当的错误。在
为此,你可以试试这个:
为期望的每个参数添加此检查。这将确保你只有数字,然后你的数学计算将工作。在
如果您知道传入的值之一必须是浮点值(即,使用小数点);然后使用
float()
转换它,否则您将得到另一个惊喜:编辑:
所以在你澄清之后,我想你想要的是:
此方法将字典作为变量;默认情况下,它为
k
求解。你可以这样称呼它:我想您要查找的函数是exec语句。您可以执行类似
exec("p='a string'")
的操作。现在您应该能够调用p
并期望'a string'
相关问题 更多 >
编程相关推荐