python中self原理实例分析

WBOY
Release: 2016-06-10 15:13:38
Original
1313 people have browsed it

本文实例讲述了python中self原理。分享给大家供大家参考。具体分析如下:

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。

假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法 MyObject.method(arg1, arg2) 的时候,这会由Python自动转为 MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。

这也意味着如果你有一个不需要参数的方法,你还是得给这个方法定义一个self参数。

示例程序:

>>> class P:
...   def selfDemo(self):
...       print 'Python, why self?'
...
...
>>> p = P()
>>> p.selfDemo()
Python, why self?
>>>
Copy after login

将selfDemo()中参数换为其他,如selfDemo(x),输出同样结果。

若不加参数,则报错:

>>> class P:
...   def selfDemo(): # have no arguments
...       print 'Python, why self?'
...
...
>>> p = P()
>>> p.selfDemo()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: selfDemo() takes no arguments (1 given)
>>>
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!