19 05 2013 Python javascript Tweet
PythonScriptではクラスがどういうjavascriptにトランスレートされるのか気になったので。
class C(): def __init__(self, x, y): self.x = x self.y = y c1 = C(1, 2) c2 = C(3, 4) print c1.x, c2.y
これは以下のjavascriptに変換される
C = {}; parents = create_array(); var C____init__ = function(args, kwargs) { var signature = {"kwargs": {}, "args": create_array("self", "x", "y")}; var arguments = get_arguments(signature, args, kwargs); var self = arguments["self"]; var x = arguments["x"]; var y = arguments["y"]; set_attribute(self, "x", x); set_attribute(self, "y", y); } C.__init__ = C____init__; C = create_class("C", parents, C); c1 = get_attribute(C, "__call__")(create_array(1, 2), {}); c2 = get_attribute(C, "__call__")(create_array(3, 4), {}); console.log(get_attribute(c1, "x"), get_attribute(c2, "y"));
create_array, get_arguments, create_class, get_attribute, set_attributeはpythonscript.jsのほうに定義されている。create_classは次のように定義されている
var create_class = function(class_name, parents, attrs) { if(attrs.__metaclass__) { var metaclass; metaclass = attrs.__metaclass__; attrs.__metaclass__ = undefined; return metaclass([class_name, parents, attrs]); } else { } var klass; klass = {}; klass.bases = parents; klass.__name__ = class_name; klass.__dict__ = attrs; var __call__ = function() { var object; object = {}; object.__class__ = klass; object.__dict__ = {}; var init; init = get_attribute(object, "__init__"); if(init) { init.apply(undefined, arguments); } else { } return object; } klass.__call__ = __call__; return klass; }