Class and object Methods

Source: Internet
Author: User

Class and object Methods

We have discussed the functions of classes and objects. Now let's take a look at its data section. In fact, they are onlyNamespace BindThat is, these names are valid only on the premise of these classes and objects.

There are two typesDomain-- Class variables and object variables, which are based on the class or objectYesThis variable is differentiated.

Class variablesShared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances.

Object VariablesIt is owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. In different instances of the same class, although the object variables have the same name, however, they are unrelated. This is easy to understand through an example.

Use the class and object variable # filename: objvar. py
Class person:
Population = 0
Def _ init _ (self, name ):
Self. Name = Name
Print ("Initializing % s") % self. Name
Person. Population + = 1
Def sayhi (Self ):
Print ("Hi, my name is % s") % self. Name
Print ('there are % d people in the world' % person. Population)
Def _ del _ (Self ):
Print "% s says goodbye" % self. Name
Person. Population-= 1
If (person. Population = 0 ):
Print 'no one in the world'
Else:
Print "there are still % d people left" % person. Population

A1 = person ("Shanshan ");
A1.sayhi ()

A2 = person ("siliang ")
A2.sayhi ()

Del A1
Del A2

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.