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)
但是,在Python中(与JavaScript不同),attribute和[]访问是不同的。说,写
^{pr2}$javascript和python之间的一个关键区别是处理方法名称空间中的目标对象。在javascript中,
this
是在方法被调用时根据需要设置的,但是在python中,self
是由类创建时间(将函数转换为instancemethod)和属性被访问时(绑定instancemethod上的im斨self属性)确定的。即使您只使用属性访问,当您想将实例方法绑定到单个实例而不是类时,克服这种差异有点棘手。在这就是它的作用:
^{pr2}$使上面的类更像},我将把这作为练习。在
dict
是一个单独的问题,在我看来,这不是JavaScript最适合模仿的“特性”,但是假设我们希望“无论如何”,我们可能会从子类化dict
开始,然后再次重载__getattr__
或{相关问题 更多 >
编程相关推荐