案例一:
1.代码
class
Python: def selfDemo(): print 'Python,why self?' p = Python() p.selfDemo()
2.执行结果
TypeError: selfDemo() takes no arguments (1 given)
eclipse提示错误信息:Method 'selfDemo - pro' should have self as first parameter


案例二:
1.代码
class
Python: def selfDemo(self): print 'Python,why self?' p = Python() p.selfDemo()
2.执行结果
Python,why self?

 

从以上两个案例,可以看出:

1.创建了一个类MyClass,实例化MyClass得到了MyObject这个对象,然后调用这个对象的方法MyObject.method(arg1,arg2),这个过程中,Python会自动转为Myclass.mehod(MyObject,arg1,arg2),这就是Python的self的原理了。即使你的类的方法不需要任何参数,但还是得给这个方法定义一个self参数,虽然我们在实例化调用的时候不用理会这个参数不用给它赋值。

2.self就是指对象的地址

posted on 2016-12-27 16:18  mangguo  阅读(252)  评论(0)    收藏  举报