Declaration of the class:
I. Properties of a class
(Private and public properties)
(Class Property)
Ii. methods of the class
(Construction method, destructor method, custom method, special member method)
(Static methods, class methods, class properties)
Iii. Inheritance of Classes
(Inheritance of methods and properties, refactoring of methods)
(abstract class, multiple inheritance)
Iv. Polymorphism of Classes
(Implementation of interface reuse)
V. Special decoration of Class
(@staticmethod, @classmethod, @property)
Vi. source and origin of classes (Metaclass)
Seven, reflection
Declaration of the class
Using class declaration classes, it is recommended to capitalize the first letter of the class list word.
The distinction between "new class" and "Classic class" does not exist after Python 3, after Python 3.x, because all classes derive from the built-in type object (even if the inherited object type is not shown), that is, all classes are "modern class."
New class:
Class Management (object): Def add (): Pass
Classic class:
Class Management:pass
public attribute : a property directly defined in a class, defined directly in the name of the class.
Invocation: 1, called in class: Class name. property name, change original public property value
2, Instance invocation: Instance. Property name
Class Management (object): num = ten def Add (self): Management.num +=10 # class calls the public property and changes the value, num=11 Passs1 = Management () s2 = Management () # First case: Public property is called in S1 instance, S2 instance does not call public property s1.num +=1management.num + = 2 "" "< result >s1 unchanged, S2 and management have changed s1_num:11 s2_num:12 manage_num:12 "" # The second case: the S1 instance public property is called first, then the add change is called through S1, and then the class change is used S1.num +=1s1.add () Management.num + = 2 "" "< results > first called S1 instance num remains unchanged, S2 and Management have been modified s1_num:11 s2_num:22 manage_num:22" ""
Question: Why does the instance S1 and instance S2 have different results after modifying the value of num?
Because the public property lookup is in the order of the public property of the instance, the public attribute in the class is not found.
It can be understood that management is the equivalent of a group, NUM is a group of photos, S1 and S2 is a group of two people.
Situation 1:s1 the photo to local, p has a double eyelid, S2 said too ugly, I will not p chart, not save. This time the photo management said I also feel ugly, the figure withdrew, re-issued a P figure. S2 can only save the latest pictures.
Situation 2:S1 Find management said your figure is too ugly, re-change it, Management said! Recall the picture modified ~
Private Properties : Add two underline, __membername, compile the time automatically add the class name, become _classname__membername, this technique is called variable name compression (mangling), in order to achieve external cannot invoke the purpose. The actual use of _classname__membername is callable, but does not conform to the rules. The standard method is obtained by defining a function.
Class Classname (object): "This is a demo!" "Def __init__ (self): Self.__membername = A. Def read_membername (self): # Standard external access method that uses functions to read private properties. return self.__membernames= Classname () print (s._classname__membername) print (S.read_membername ()) "< results >8888 ------like the following call, there will be a attributeerror error------print (s.__membername) "
class Properties : The properties of the class, note that the instantiated class attributes are different from the class properties of the original class. Use the example above for a demonstration.
Property
|
Role
|
Example
|
Results
|
| __doc__ |
The document string for the class |
Print (s.__doc__) Print (classname.__doc__) |
This is a demo! This is a demo! |
| __dict__ |
A dictionary of the properties of a class |
Print (s.__dict__) Print (classname.__dict__) |
{' _classname__membername ': 88} {' __init__ ':, ' __module__ ': ' __main__ ', ' __doc__ ': ' \nthis is a demo!\n ', ' Read_membername ':} |
| __name__ |
The name of the class (string) |
# #不能用于实例print (s.__name__) Print (classname.__name__) |
Classname |
| __bases__ |
A tuple that consists of all the parent classes of the |
#不能用于实例print (s.__bases__) Print (classname.__bases__) |
(,) Why is there no value? Could be a compiler problem |
| __module__ |
module to which the class belongs |
Print (s.__module__) Print (classname.__module__) |
__main__ __main__ |
| __class__ |
Type of class object |
Print (s.__class__) Print (classname.__class__) |
Pending test
|
| __slots__ |
Qualifying class properties, defining in class Property location Properties that are not defined in slots are illegal |
__slots__. (' name ', ' age ', ' sexy ') |
Use ' name ', ' age ', ' sexy ' outside of the attribute will be error |
Methods of the class
A method of a class is a function defined within a class. Class construction methods, destructor methods, custom class methods, static methods, class methods, property methods, special member methods.
Construction Method: __init__
Functions that are run when the class is instantiated. The parameters you want to initialize are placed under init. (personally think, this initialization parameter can be all objects!) )
Class A (object): Def instense (self): print ("Init obj-A") class B (object): Def __init__ (self, para): Self.init_para = PA RA self.obj_a = A () Self.num = 1 def show (self): print (Self.init_para) self.obj_A.instense () print (self.num) haha = B ("This is Para") haha.show ()----------the is Parainit obj A1
destructor Method:
__del__: The method executes when the instance is destroyed.
Class Hello (object): Def __del__ (self): print ("You deleted the instance") # Test instance = Hello () del instance# on Python of course you can also use instance invocation, but It's not so used. ~~INSTANCE.__DEL__ ()
Custom methods:
Remove the function that starts with an underscore in the class, and define a function in the class to implement the corresponding function.
class Person (object): Def __init__ (Self,person_name, Person_age)
static method:
@staticmethod, you do not need to access any parameters in the class. The parameters that are taken are imported from the outside.
class Person (object): Def __init__ (Self,person_name, person_age): Self.name = person_name self.age = pers On_age @staticmethod def info (country): Print (country)
class Method:
@classmethod, the first argument must be a class property.
class Person (object): Country = "China" def __init__ (Self,person_name, person_age): Self.name = Person_name Self.age = person_age @classmethod def info (country): Print (country)
Property Method:
@property turn a function into a static property
Call the function name directly, without parentheses, you can get the function return value. Generally used in not pay attention to the process, as long as the results of the situation!
class Person (object): Country = "China" def __init__ (Self,person_name, person_age): Self.name = Person_name Self.age = Person_age @property def health_point (self): print ("HP:" {} "". Format (self.age*2)) Retu RN self.age*2p = person ("Laowang", "Total") P.health_point # does not need parentheses, it looks completely an attribute, this is the property method
Special member methods:
Method
|
Role |
Example |
Results |
__call__
|
Not defined by default After the class is instantiated, the method that invokes the instance runs
|
p = person () P ()
|
Person is the class name Instance p does not call the function, plus () run the Invoke method
|
__str__
|
Not defined by default, must have a return value when defined When defining, print the instance, enter the STR return value
|
p = person () Print (P) |
Person is the class name Print instance p, run the Str method, print the return value |
__getitem__
|
Used for index operations, such as dictionaries. Get Data |
p = person () p[' name '] |
Run GetItem automatically
|
__setitem__
|
Used for index operations, such as dictionaries. Assign value |
p = person () p[' name '] = ' David ' |
Run SetItem automatically |
__delitem__
|
Used for index operations, such as dictionaries. Delete data |
p = person () Del p[' name '] |
Run Delitem automatically |
__new__
|
When a class is instantiated, it executes __new__ and blocks Init run, you can call init in new
|
p = person () |
Reference Example II
|
__len__
|
Cond
|
|
|
| __cmp__ |
Cond |
|
|
Example two: __new__/__init__ ' class Person (object): Def __init__ (self): print (' This is init! ') def __new__ (self): print ("This is new!") Self.__init__ (self) # If this line is removed, init cannot execute P = person ()
the source and meta class of the class:
HTTP://BLOG.JOBBOLE.COM/21351/Chinese version of the detailed answer. Write a simple version of your own understanding below.
First, the class is also an object, which can:
1) You can assign it to a variable
2) You can copy it
3) You can add properties to it
4) You can pass it as a function parameter
Class is also created by the function type (), type is the class class, the father of the class. Learn to name the META Class!
Maybe someone will ask why type () can look up the data type? Because data types are class-defined in Python, it also explains why numbers, characters, and so on are all objects.
Type format:
The type (class name, (parent class tuple), {attribute dictionary},{Method Dictionary}), parent class tuple can be absent, the default value is none when the following two code is omitted.
"' An example of a word '" class person (object): Country = ' China ' person = type (' Person ', (' object '), {' Country ': ')
Not to be continued ...
Python Basics: Python class (really tired ~)