Python要self的理由
2014-08-22 20:04
148 查看
为何Python给self赋值而你不必给self赋值?
例子说明:创建了一个类MyClass,实例化MyClass得到了MyObject这个对象,然后调用这个对象的方法MyObject.method(arg1,arg2) ,这个过程中,Python会自动转为Myclass.mehod(MyObject,arg1,arg2)这就是Python的self的原理了。即使你的类的方法不需要任何参数,但还是得给这个方法定义一个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能避免非限定调用造成的全局变量。在Python3之后不知道将self隐了没?感觉在Python类里的方法都要带个self这样有点死板
相关文章推荐
- Python要self的理由
- Python要self的理由
- Python要self的理由
- Python要self的理由
- 细数Python让人着迷的十二大理由
- python self __init__
- python self,cls,decorator的理解
- 国际:Ruby、Python不能威胁Java的13个理由
- 使用Python的理由
- 深入理解python之self
- Python中self的理解
- 选择Python的理由
- python __str__(self) __unicode__(self)
- python 参数列表中的self 显式不等于冗余
- 应该向网络开发初学者推荐PHP、Python还是Ruby?你的理由是什么?
- 关于python中self
- 国际:Ruby、Python不能威胁Java的13个理由
- python中类中函数参数self
- python 参数列表中的self 显式不等于冗余
- python里的self