如何将此JavaScript代码转换为Python代码?

时间:2019-07-23 17:41:47

标签: javascript python function

对不起,我知道这可能是一个奇怪的问题,但是我制作了这个基本的JavaScript程序,但我不确定我应该如何查找才能将其翻译为具有相同功能的python程序。我知道代码是如何工作的,但是我不知道它的技术术语是什么,因此我努力寻找如何在python中进行操作。任何帮助将不胜感激。谢谢!


var myArray = [];

var myCache = {

    add: function a(x){
        myArray.shift();
        myArray.push(x);
    },

    access: function b(z){
        var zLocation = myArray.indexOf(z);
        var temp1 = myArray.slice(0,zLocation);
        var temp2 = myArray.slice(zLocation+1, myArray.length);
        temp1 = temp1.concat(temp2);
        temp1.push(z);
        myArray = temp1;
    },

    print: function c(){
        console.log("Current array is: " + myArray);
    },

    size: function d(y){
        yArray.length = y;
    }
};

myCache.add(7); 

我不知道如何向我在Python中创建的内容添加添加,访问,打印和调整大小功能。谢谢!

2 个答案:

答案 0 :(得分:0)

只需使用Js2PY。它是用Python编写的,因此您当然必须拥有Python,但除此之外,您的好处还不错。如果您想走很长一段路,那么学习Python会更好,因为一旦您在Python中有了代码,便知道如何对其进行更改。

答案 1 :(得分:0)

由于python是一种面向对象的语言,因此获取对象的方法基本上是创建一个类,该类充当该对象的不同实例的蓝图/原型。因此,翻译为python的代码或多或少看起来像这样:

(大家都是python专家,请原谅我,我不是= D)

class MyCache:
    def __init__(self, *args, **kwargs):
        # in python the most similar to a javascript array is a list
        # to make it a bit more readable `myArray` is called `_cache` here
        self._cache = []

    def add(self, x):
        # do not try to pop() from an empty list, will throw an error
        if self._cache:
            self._cache.pop(0)

        self._cache.append(x)

    def access(self, z):
        # index() is a bit whimpy in python...
        try:
            i = self._cache.index(z);
            # I think we don't need the .slice() stuff here,
            # can just .pop() at the index in python
            self._cache.pop(i)
            self._cache.append(z)
        except ValueError as err:
            print(err)

    def size(self, y):
        # not sure what you want to do here, initialize the cache with
        # an array/list of a specific length?
        self._cache = [None] * y

    # print is a reserved word in python...
    def status(self):
        print("Current array is: ")
        print(self._cache)

# instantiate the class (e.g. get a cache object)
# and do some stuff with it..
cache = MyCache()
cache.add(7)
cache.status()
cache.add(10)
cache.status()
cache.add(3)
cache.status()
cache.access(3)
cache.status()

不确定这是否确实在执行您期望的操作,由于add()方法将始终删除一个值,因此缓存中始终只有1个值,因此{{1 }}方法的种类没有意义...但是也许只是您的简化示例代码?