Examples of self principles in python

Source: Internet
Author: User
This article mainly introduces the self principle in python, analyzes in detail the self principle and related usage skills, and has some reference value, for more information about the self principle in python, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:

Class methods have only one special difference from common functions-they must have an additional first parameter name, but you do not assign a value to this parameter when calling this method, python provides this value. This special variable refers to the object itself, which is named self by convention.

Assume that you have a class named MyClass and an instance named MyObject of this class. When you call this object method MyObject. method (arg1, arg2), this will be automatically converted from Python to MyClass. method (MyObject, arg1, arg2) -- this is the principle of self.

This also means that if you have a method that does not require a parameter, you still have to define a self parameter for this method.

Example program:

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

Replace the parameters in selfDemo () with other parameters, such as selfDemo (x), and output the same result.

If no parameter is added, an error is returned:

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

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.