Class variables and object variables in python

Source: Internet
Author: User

Due to recent work needs, I began to use the python language. He is experiencing his novelty. The first concept that puzzles me is class variables and object variables.

Although they can be easily mapped to static members and common members of classes in object-oriented languages such as C ++, I personally think the concept of object variables is too flexible. For example

#! /Usr/bin/python
# Filename: object. py

Class Person:
Countofperson = 0
Def _ init _ (self, name ):
Self. name = name

Print '(Initializing % s)' % self. name

 

There is such a class <person> that defines the variable name of the object and the number of class variable persons countofpersion according to python. One drawback is that the class is not intuitively displayed in front of people, because the object variable is hidden in the class-Defined Function member, people may not be able to focus on the variables of all objects in a class immediately.

 

To ensure this, we recommend that you use the _ name method to define the object variables for class clarity. This ensures that the variables only act on objects and the definition of classes, meets regular programming specifications. Why not? The above code can be rewritten

#! /Usr/bin/python

# Filename: object. py

Class Person:
Countofperson = 0
_ Name = []

Def _ init _ (self, name ):
Self. _ name = name

Print '(Initializing % s)' % self. _ name

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.