The difference between a Python class variable and an instance variable

Source: Internet
Author: User

Class variables: are services for the class, all instances of the class are shared, changed in one place, and all the values of the local variables of the call change. The class is defined as the class name. Variable name instance variable: In the instance, the value of each instance variable is modified according to the requirements of the instance itself, does not affect other instances, and the class is defined as self. The variable name (1) defines a class c:a = 0 #类变量 b = 0 #类变 Volume Def __init__ (self, flag): SELF.A = Flag #实例变量 C.A = 1 #类变量赋值 c.b = 1 #类变量赋值 (2) Class instantiation test1 = C (5) Test2 = C (6) (3) View results >>> test1.a5>>> test2.a6# instance variables have different values depending on the instance >>> c.a1> >> c.b1>>> test1.b1>>> test2.b1# class variables are the same in all instances >>> c.b = ten #改变类变量值 >>> test1. B10>>> test2.b10# can see that the class variables in all instances have changed

The difference between a Python class variable and an instance variable

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.