Python中的Javascriptstyle对象方法?

2024-05-28 23:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在Javascript中,我可以这样做:

var person = {
  name: 'Joe',
  age:  '35',
  speak: function(){
    return 'o hai i am joe'
  }
}

然后我可以将该方法称为:

^{pr2}$

我知道这可以用Python中的类来实现,这大概是正确的方法。在

尽管如此,我很好奇——有没有什么方法可以将函数作为值添加到Python字典中?在


Tags: 方法函数nameagereturnvarfunctionjavascript
3条回答
def test():
    print "hello"

testDict = {"name" : "Joe", "age" : 35, "speak" : test}

testDict["speak"]()
person = {
  'name': 'Joe',
  'age':  '35',
  'speak': lambda: 'o hai i am joe',
}

但是,在Python中(与JavaScript不同),attribute和[]访问是不同的。说,写

^{pr2}$

javascript和python之间的一个关键区别是处理方法名称空间中的目标对象。在javascript中,this是在方法被调用时根据需要设置的,但是在python中,self是由类创建时间(将函数转换为instancemethod)和属性被访问时(绑定instancemethod上的im斨self属性)确定的。即使您只使用属性访问,当您想将实例方法绑定到单个实例而不是类时,克服这种差异有点棘手。在

import functools
class JSObject(object):
    def __getattribute__(self, attr):
        """
        if the attribute is on the instance, and the target of that is
        callable, bind it to self, otherwise defer to the default getattr.
        """
        self_dict = object.__getattribute__(self, '__dict__')
        if attr in self_dict and callable(self_dict[attr]):
            return functools.partial(self_dict[attr], self)
        else:
            return object.__getattribute__(self, attr)

这就是它的作用:

^{pr2}$

使上面的类更像dict是一个单独的问题,在我看来,这不是JavaScript最适合模仿的“特性”,但是假设我们希望“无论如何”,我们可能会从子类化dict开始,然后再次重载__getattr__或{},我将把这作为练习。在

相关问题 更多 >

    热门问题