Python Learning (21) -- Python static variables

Source: Internet
Author: User

I have been using python for testing for a long time and may not have a deep understanding. Someone asked me in the Forum some time ago,

Class Foo ():
Member1
Member2
...
Self. member1
Foo. member2

What is the difference between two members, member1 and member2... This means that python also has its own Global static variables.

The attributes of its instance are instances. When you perform the +/-operation on member1 in the above class, it will only affect the corresponding object instance, (its class and other instances of this class are not affected ).

If the class property is a mutable object, the modification to this object * itself * will be reflected to all other instances.Static member variables defined in Python are class variables and can only be passed throughClass. variable nameIn the form

A class variable is a variable member shared by all objects of the class,

Class A: A1 = 0 def _ init _ (self, A2): Self. a2 = a2 def setdata (self, A3): Self. a3 = A3 def show (Self): Print 'a1: % s, A1: % s, A2: % s, A3: % s' % (. a1, self. a1, self. a2, self. a3) If _ name _ = '_ main _': obj1 = A (1) obj2 = a (2) obj3 = A (3) obj1.setdata (1) obj2.setdata (2) obj3.setdata (3) obj1.a1 = 1 obj2.a1 = 2 obj3.a1 = 3. a1 = 1. a2 = 2. a3 = 3 obj1.show () obj2.show () obj3.show () print 'a1: % s, A2: % s, A3: % s' % (. a1,. a2,. a3)

Output result:

A1: 1, A1: 1, A2: 1, A3: 1
A1: 1, A1: 2, A2: 2, A3: 2
A1: 1, A1: 3, A2: 3, A3: 3
A1: 1, A2: 2, A3: 3

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.