Python class variables and instance variables

Source: Internet
Author: User

Python's class variables and instance variables, as the name implies, class variables are the variables with the class, and instance variables, refers to the specific instance of the class is associated with the variable, specifically reflected as self.x, etc. The association between a class variable and an instance variable that you actually want to notice. And class methods can also be accessed through the class, or through the instance, class variables can be accessed either through an instance or through a class.

See Example:

Person:    Name="aaa" P1=person () P2=person () p1.name="BBB" # This modifies the P1.name reference so that it no longer points to the class variable, but becomes an instance variable # BBB# AAA# AAA        

A class variable is a variable that is used by a class, and an instance variable is used by an instance.

Here p1.name="bbb" is the instance called the class variable, which is actually the same as above the first problem, is the function of the argument, the first p1.name is a pointer to the class variable, but in the scope of the name="aaa" instance of the class variable to change the reference, it becomes an instance variable, Self.name no longer references the class variable name of person.

Take a look at the following example:

Person:    name=[]p1=person () P2=person () p1.name.append (1) #p1.name still points to the class variable, so modifications to it directly affect the class variable. # [1]# [1]# [1]      

Python class variables and instance variables

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.