标签:
js里,一个对象new 以后 可以绑定方法
var Point=function(x) {this.x=x}
undefined
var p=new Point(1)
undefined
p.run=function(){return ‘echo from p.run...‘} //和p.x没关系
[object Function]
p.run()
"echo from p.run..."
p.getx=function(){return this.x} //使用 this.x
[object Function]
p.getx()
1
python
>>> p=Point(1) >>> def run(): return ‘echo from p.run...‘ >>> p.run=run >>> p.run() #和self.x没关系 ‘echo from p.run...‘ >>> import types >>> def getx(self): return self.x >>> p.getx=types.MethodType(getx,p) #对象绑定需要操作self的方法,需要使用type.MethodType >>> p.getx() 1 >>>
js定义类时, 类名.prototype.方法名=function(){;};
python 在类定义好以后,可以使用types.MethodType后绑定.或 类名.方法名=方法名(self,[...]) : pass 去定义
标签:
原文地址:http://www.cnblogs.com/Citizen/p/4934925.html