Self of Python (go)

Source: Internet
Author: User

The first thing to be clear is that self is only available in the methods of the class, and independent functions or methods do not have to have the. Self is necessary when defining a method of a class, although it is not necessary to pass in the appropriate arguments when calling.

Self name is not necessary, in Python, self is not a keyword, you can be defined as a or B or other names can be, but the agreement idiomatic, do not engage in alternative, we will not understand. The following example changes self to myname without errors:

1 class Person:
2 def _init_ (myname,name):
3 Myname.name=name
4 def sayhello (myname):
5 print ' My name is: ', myname.name
6 P=person (' Bill ')
7 Print P

Self refers to the class instance object itself (note: 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

在上述例子中,self指向Person的实例p。 为什么不是指向类本身呢,如下例子:

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, then when there are multiple instance objects, which one does it point to?

Self of Python (go)

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.