读书人

Python为何要self

发布时间: 2013-07-01 12:33:04 作者: rapoo

Python为什么要self
class Python: def selfDemo(self): print('Python,why self?')p = Python()p.selfDemo()

输出:Python,why self?

把p.selfDemo()带个参数如:p.selfDemo(p),得到同样的输出结果

如果把self去掉的话,

class Python: def selfDemo():  print('Python,why self?')p = Python()p.selfDemo()

?这样就报错了:TypeError: selfDemo() takes no arguments (1 given)

?

扩展

self在Python里不是关键字。self代表当前对象的地址,self 其实就是class中instance,譬如static method 是不需要加self的, 譬如non-static method 有时候用className.method() 也是可以的。self能避免非限定调用造成的全局变量。

读书人网 >perl python

热点推荐