【发布时间】:2014-04-25 15:18:37
【问题描述】:
我的项目涉及将 Python 2.7 代码转换为 Dart 代码。为了完全模拟 Python 数据类型的所有特性,我在 Dart 中创建了包装类,它扩展了原始 Dart 数据类型的功能以匹配相应的 Python 类型。所有类型都有包装器,例如用于数字的 $PyNum、用于字符串的 $PyString 等等。一切都很好,翻译后的代码工作正常。代码如下:
def fib(n):
if n <= 2:
return 1
else:
return fib (n - 1) + fib (n - 2)
print (fib(36))
对应生成的Dart代码为:
import 'lib/inbuilts.dart';
import 'dart:io';
fib(n) {
if (n <= new $PyNum(2)) {
return new $PyNum(1);
} else {
return (fib((n - new $PyNum(1))) + fib((n - new $PyNum(2))));
}
}
main() {
stdout.writeln(fib(new $PyNum(36)));
}
代码运行良好,但在此类存在极端递归的代码中,在每个函数实例处创建的过多包装器对象对代码的运行时间造成严重影响。例如展开的 Dart 代码:
import'dart:io';
fib(n) {
if (n <= 2) {
return 1;
} else {
return (fib((n - 1)) + fib((n - 2)));
}
}
main() {
stdout.writeln(fib(36));
}
由于显而易见的原因,它的运行速度几乎比包装代码快 15 倍。所有涉及包装数据类型的计算都会返回该类的新实例。对我来说,通过 Dart 模拟 Python 在其数据类型中提供的所有功能绝对至关重要,而包装是我目前唯一想到的事情。 我尝试使用单例类创建一个通用对象进行计算,但在递归和线程情况下失败。
我的 $PyNum 包装类是这样的:
class $PyNum {
num _value;
$PyNum(value) {
switch ($getType(value)) {
case 6:
_value = value;
break;
case 7:
try {
_value = num.parse(value);
} catch (ex) {
print("Invalid string literal for num parsing");
exit(1);
}
break;
case 5:
_value = value.value();
break;
default:
throw "Invalid input for num conversion";
}
}
value() => _value;
toString() => _value.toString();
operator +(other) => new $PyNum(_value + other.value());
operator -(other) => new $PyNum(_value - other.value());
operator *(other) => new $PyNum(_value * other.value());
operator ~/(other) => new $PyNum(_value ~/ other.value());
operator |(other) => new $PyNum(_value | other.value());
operator &(other) => new $PyNum(_value & other.value());
operator ^(other) => new $PyNum(_value ^ other.value());
operator %(other) => new $PyNum(_value % other.value());
operator <<(other) => new $PyNum(_value << other.value());
operator >>(other) => new $PyNum(_value >> other.value());
operator ==(other) {
switch ($getType(other)) {
case 6:
return _value == other;
case 5:
return _value == other.value();
default:
return false;
}
}
operator <(other) {
switch ($getType(other)) {
case 6:
return _value < other;
case 5:
return _value < other.value();
default:
return true;
}
}
operator >(other) => !(this < other) && (this != other);
operator <=(other) => (this < other) || (this == other);
operator >=(other) => (this > other) || (this == other);
}
$getType(variable) {
if (variable is bool)
return 0;
else if (variable is $PyBool)
return 1;
else if (variable is $PyDict)
return 2;
else if (variable is $PyList)
return 3;
else if (variable is List)
return 4;
else if (variable is $PyNum)
return 5;
else if (variable is num)
return 6;
else if (variable is $PyString)
return 7;
else if (variable is $PyTuple)
return 8;
else
return -1;
}
可以从这个类中取出 const 对象吗?我不太清楚该怎么做。
有没有其他方法可以有效地做到这一点并且仍然能够模拟 Python 的所有功能?非常感谢任何帮助!
【问题讨论】:
标签: python oop python-2.7 dart wrapper