Python 到 Javascript

遍历

python中的for循环很方便,但js中等价的写法 不是 for/in,for/in 语句循环遍历对象的属性:如要遍历打印数组的元素js用forEach

python:

>>> a = [1,2,3,4]

>>> for n in a:

             print n

javascript:

a = [1,2,3,4]

a.forEach(function(n){

    alert(n)

})

闭包

# python 闭包就好像只有一个方法的类
>>> def sandwich_maker(magic_ingredient):
        def make(filling):
            return magic_ingredient + ' and ' + filling
        return make

>>> ham_and = sandwich_maker('ham')
>>> ham_and('cheese')
'ham and cheese'
>>> ham_and('mustard')
'ham and mustard'
>>> turkey_and = sandwich_maker('turkey')
>>> turkey_and('swiss')
'turkey and swiss'
>>> turkey_and('provolone')
'turkey and provolone'

 

function sandwichMaker(ingredient){
	function make(filling){
		return ingredient + ' and ' + filling;
	}
	return make
}

var hamAnd = sandwichMaker('ham')

hamAnd('cheese')
"ham and cheese"
hamAnd('mustard')
"ham and mustard"
var turkeyAnd = sandwichMaker('turkey');

turkeyAnd('swiss')
"turkey and swiss"
turkeyAnd('Provolone')
"turkey and Provolone"

 

但是在python中我觉得完全可以用类来写,看着更习惯吧,在js中函数就是类,在python中这样想也好理解

>>> class SandwichMaker():
        def __init__(self, magic_ingredient):
            self.magic_ingredient = magic_ingredient
        def make(self, filling):
            return self.magic_ingredient + ' and ' + filling
        def make2(self, filling):
            return self.magic_ingredient + ' and ' + filling
>>> ham_and = SandwichMaker('ham')
>>> ham_and.make('cheese')
'ham and cheese'
>>> ham_and.make('mustard')
'ham and mustard'
>>> turkey_and = SandwichMaker('turkey')
>>> turkey_and.make('swiss')
'turkey and swiss'
>>> turkey_and.make('provolone')
'turkey and provolone'

# 把类改成函数是不是很像,但方法多了调用起来麻烦,所以类就是一个改造过的函数
>>> def SandwichMaker(magic_ingredient):
        magic_ingredient = magic_ingredient
        def make(filling):
            return magic_ingredient + ' and ' + filling
        def make2(filling):
            return magic_ingredient + ' and ' + filling
        return make, make2

>>> ham_and = SandwichMaker('ham')
>>> ham_and[0]('cheese')
'ham and cheese'
>>> ham_and[0]('mustard')
'ham and mustard'
>>> turkey_and = SandwichMaker('turkey')
>>> turkey_and[0]('swiss')
'turkey and swiss'
>>> turkey_and[0]('provolone')
'turkey and provolone'
>>>

 

相关推荐