1. Self, CLS is not a keyword
In python, self and Cls are not keywords and can be replaced by any variable you write.
Code 1
Copy code The Code is as follows: Class mytest:
Myname = 'Peter'
Def sayhello (Hello ):
Print "Say hello to % s" % Hello. myname
If _ name _ = "_ main __":
Mytest (). sayhello ()
In code 1, self is replaced with Hello, which achieves the same effect and can be replaced with this, which is commonly used in Java.
Conclusion: Self and Cls are just written as agreed in Python. They are essentially just a function parameter and have no special meaning.
Any object that calls a method will pass itself as the first parameter in the method to the function. (Because everything in python is an object, when we use class. Method (), the first parameter is actually our agreed CLs)
2. The class definition can be dynamically modified
Code 2Copy codeThe Code is as follows: Class mytest:
Myname = 'Peter'
Def sayhello (Self ):
Print "Say hello to % s" % self. myname
If _ name _ = "_ main __":
Mytest. myname = 'hone'
Mytest. sayhello = Lambda self, name: "I want say hello to % s" % name
Mytest. saygoodbye = Lambda self, name: "I do not want say goodbye to % s" % name
Print mytest (). sayhello (mytest. myname)
Print mytest (). saygoodbye (mytest. myname)
The variables and function definitions in the mytest class are modified here, And the instantiated instance has different behavior characteristics.
3. decorator
Decorator is a function that receives a function as a parameter and returns a function.
Code 3Copy codeThe Code is as follows: def enhanced (METH ):
Def new (self, Y ):
Print "I am enhanced"
Return meth (self, Y)
Return new
Class C:
Def bar (self, X ):
Print "some method says:", X
Bar = enhanced (bar)
The above is a typical application
Take the commonly used @ classmethod as an Example
The normal method is
Code 4Copy codeThe Code is as follows: Class C:
@ Classmethod
Def Foo (CLS, Y ):
Print "classmethod", CLS, y
There is a doubt here, not quite clear: if a method does not use @ classmethod, then the class. Method () method will report an error. But @ classmethod is a decorator, so it returns a function. why can it be directly called by class?