Python: class attributes, instance attributes, private attributes and static methods, class methods, instance methods, and python private
From: http://www.cnblogs.com/pengsixiong/p/4823473.html
Attributes include instance attributes and class attributes.
Methods can be classified into common methods, class methods, and static methods.
I. attributes:
Try to use the attributes that need to be passed in as instance attributes, and the attributes of the same type as the class attributes. The instance attributes are initialized every time a class is created. The instance attributes of different instances may be different, and the class attributes of different instances are the same. This reduces memory usage.
1: instance attributes:
It is best to initialize in _ init _ (self ,...)
Self must be added for internal calls.
Use instancename. propertyname for external calls
2: class attributes:
Initialize outside _ init _ ()
Use classname. Class Name internally
You can use either the classname or the instancename.
3: Private attributes:
1): starts with an underscore (_). It only tells others that this is a private property and can still be accessed and changed externally.
2): Double underline _ start: the external cannot be accessed or changed through instancename. propertyname
Actually convert it to _ classname _ propertyname
Ii. Method
1: Common class method:
Def fun_name (self ,...):
Pass
External instance call
2: static method: @ staticmethod
Unable to access instance attributes !!! The parameter cannot be passed in self !!!
Class-related but not dependent on the class and instance methods !!
3: Class Method: @ classmethod
Unable to access instance attributes !!! The parameter must be passed in cls !!!
You must pass in the cls parameter (that is, the object that represents this class ----- difference ------ self represents the Instance Object), and use this to electrophoresis class property: cls. Class property name
* Both static and class methods can be called through classes or instances. Both of them are characterized by the inability to call instance attributes.
E. g1:
- Class:
- Member = "this is a test ."
- Def _ init _ (self ):
- Pass
-
- @ Classmethod
- Def Print1 (cls ):
- Print "print 1:", cls. member
- Def Print2 (self ):
- Print "print 2:", self. member
- @ Classmethod
- Def Print3 (paraTest ):
- Print "print 3:", paraTest. member
- @ Staticmethod
- Def print4 ():
- Print "hello"
Summary: class attributes and class methods are inherent methods and attributes of the class. They are not changed because of different instances. The purpose of writing them is to reduce the memory space created when multiple instances exist, speed up operation.