Python要self的理由
来源:互联网 发布:淘宝详情图片格式 编辑:程序博客网 时间:2024/05/18 05:07
为何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这样有点死板
0 0
- Python要self的理由
- Python要self的理由
- 选择Python的理由
- 使用Python的理由
- 选择Python的理由
- 选择python的理由?
- python里的self
- 关于python的self
- python self的解释
- Python 为什么要self
- Python为什么要self
- Python为什么要self
- Python为什么要self
- Python为什么要self
- Python为什么要self
- Python为什么要self
- 【Python】选择ipython替代python的理由
- Python中self的理解
- Java异常处理(try、catch、finally使用)
- 一个自定义注释的例子
- linux用户栈和内核栈
- POJ 3036 Honeycomb Walk(DP)
- 【leetcode】two-sum
- Python要self的理由
- poj 2533 Longest Ordered Subsequence
- 使用Dom4j解析xml文件---DomReader方式
- 数据结构——顺序栈与链栈的C++实现
- 黑马程序员——Java泛型通配符的总结
- strcpy函数的实现
- UVA - 11292 Dragon of Loowater
- 计算机网络
- IOS 连续图片组成的动画