Deep understanding of Python self

Source: Internet
Author: User

First, it is clear that self is only available in class methods. Independent functions or methods do not have to carry self. Self is required when defining class methods, although you do not need to input the corresponding parameters during the call.

Self names are not mandatory. in Python, self is not a keyword. You can define it as A, B, or other names, you will not understand. In the following example, there is no error in changing self to myname:

1 ClassPerson:
2Def_ Init _ (myname, name ):
3Myname. Name = Name
4DefSayhello (myname ):
5Print 'My name is:', Myname. Name
6P = person ('Bill')
7 PrintP

Self refers to the class instance object itself (Note: it is not the class itself ).

  1   class  person: 
2 def _ init _ (self, name):
3 self. name = Name
4 def sayhello (Self):
5 Print ' my name is: ', self. name
6 P = person ( ' Bill ')
7 Print P

in the preceding example, Self point to instance P of person. Why not point to the class itself, as shown in the following example:

1   Class Person:
2 Def _ Init _ (self, name ):
3 Self. Name = Name
4 Def Sayhello (Self ):
5 Print ' My name is: ' , Self. Name
6 P = person (' Bill ' )
7 P1 = person ( ' Apple ' )
8 Print P

If Self points to the class itself, which one does self point to when there are multiple instance objects?

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.