Python class variable and instance variable difference

Source: Internet
Author: User

Deep understanding of Python class instance variables and class variables The nature of Python variables: Assigned values
1 Ordinary Python variables (non-class related variables) are easy to understand, after being assigned the variable exists, readable and writable
2 variables of the Python class (class variables and instance object variables) are assigned in some way, that is, exist, can be read and written
2.1 Python class variable is assigned value
(1) in the design of the class,
In class Def, the variable name can be assigned
In Def, the name of a point operation variable named by a class object is a class name that can be assigned
(2) in the program
A class name can also be assigned by a class object (class name).
2.2 Python Instance object variable is assigned value
(1) Design time of class
In Def, the variable name can be assigned through the self-point operator, not necessarily in Init, but also in other called method functions.
(2) in the program
The point operator variable name can be assigned by the instance object
Example:
classaa:w= 10def __init__(self): self.x= 11Self.y= 12defAdd (self):returnSelf.x +Self.ya=AA ()Print(A.add ())//Output#what is the function of the two instructions below? The result is output of two 20? Or is it a two 13? Still is? AA.W = 20A.W= 13Print(AA.W, A.W)//Output#The program continues to increase as follows, how to understand this T and Q? They are instance variablesA.T = 14A.Q= 15Print(A.T, A.Q)//Output#The procedure continues to increase as follows, how to understand this m and n? They are class variablesAA.M = 30AA.N= 40Print(AA.M, AA.N)//input#All right, let's get another boost.#The program continues to increase, the following three print statements can be executed correctly? Why? b =AA ()Print(b.x, B.Y)Correct output 11 12
Print

Print (B.M, B.N)//correct output 30 40

Python class variable and instance variable difference

Related Article

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.