最近在看python的一些代码,学习并且要掌握这些在短期内还是有一点难度的,日积月累,浮躁是个大问题。对于一个基本没从事过开发的我来说,看到python self这个值的时候很不理解,也不知道它的含义是什么,后面经查阅相关资料才得以弄明白。
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。 虽然你可以给这个参数任何名称,但是强烈建议你使用self这个名称——其他名称都是不赞成你使用的。使用一个标准的名称有很多优点——你的程序读者可以迅速识别它,如果使用self的话,还有些IDE(集成开发环境)也可以帮助你。 你 一定很奇怪Python如何给self赋值以及为何你不需要给它赋值。举一个例子会使此变得清晰。假如你有一个类称为MyClass和这个类的一个实例 MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。
这也意味着如果你有一个不需要参数的方法,你还是得给这个方法定义一个self参数。
实例1:
========================================================================== In [1]: class Testself: def testself(self): print "hello self!" In [2]: p=Testself() In [3]: p.testself() hello self! In [4]: #如果去掉self的话就会报错 n [6]: class Testself: def testself(): print "hello self!" In [9]: p=Testself() In [10]: p.testself() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/users/wul/python/<ipython console> in <module>() TypeError: testself() takes no arguments (1 given) In [11]: ==========================================================================
类将它们的第一个参数绑定到所属的实例上,这正是类和函数的区别。可以将特性绑定到一个普通函数上,这样就不会有特殊的self参数了 实例2:
========================================================================== In [26]: class Testself1: ....: def testself1(self): ....: print 'self is must!' ....: ....: In [27]: def testself2(): ....: print 'There is no self!oh yeah!' ....: ....: In [28]: test=Testself1() In [29]: test.testself1() self is must! In [30]: test.testself1 = testself2 In [31]: test.testself1() There is no self!oh yeah! ==========================================================================
参考文章:简明 Python 教程 http://woodpecker.org.cn/abyteofpython_cn/chinese/ch11s02.html Python基础编程
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有