我是IronPython和Python的新手。我正在尝试使用C#小数和IronPython数学函数。当我尝试返回参数的绝对值时,当参数是小数时,我得到一个类型异常。这是我的代码:
[TestMethod]
public void CallDecimal()
{
var pySrc =
@"def MyAbs(arg):
return abs(arg)";
// host python and execute script
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
engine.Execute(pySrc, scope);
// get function with a strongly typed signature
var myAbs = scope.GetVariable<Func<decimal, decimal>>("MyAbs");
Assert.AreEqual(5m, myAbs(-5m));
}
我得到的错误信息是:
IronPython.Runtime.Exceptions.TypeErrorException: bad operand type for abs(): 'Decimal'
是否有接受小数的Python绝对值函数?如果没有,写一个是否容易?如果我可以指定函数参数的类型,我会尝试创建我自己的abs函数:
define abs(Decimal arg):
return arg < 0 ? -arg : arg
答案 0 :(得分:1)
您始终可以选择导入.NET Math
类并使用那里的方法。
var pySrc =
@"def MyAbs(arg):
from System import Math
return Math.Abs(arg)";