1. Self, CLS is not a keyword
Inside Python, self, the CLS is not a keyword, you can use any variable you write instead of implementing the same effect.
Code 1
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, use Hello instead of self, get the same effect, you can also replace the common in Java this.
Conclusion: The self and the CLS are just the conventions in python, essentially a function parameter, with no special meaning.
Any object invocation method will pass itself as the first parameter in the method to the function. (because everything in Python is an object, so when we use Class.method (), the first parameter is actually the CLS we agreed on)
2. The definition of a class can be modified dynamically
Code 2
The 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 don't want Say goodbye to%s"% name
Print MyTest (). SayHello (Mytest.myname)
Print MyTest (). Saygoodbye (Mytest.myname)
This modifies the variables and function definitions in the MyTest class, and the instantiated instance has different behavioral characteristics.
3. Decorator
Decorator is a function that receives a function as an argument, and the return value is a function
Code 3
The 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 more typical application
Take the commonly used @classmethod as an example
The normal way to use it is
Code 4
The code is as follows:
Class C:
@classmethod
def foo (cls, y):
Print "Classmethod", CLS, y
Here is a puzzled place, not very clear: if a method does not use @classmethod, then use Class.method () way, will be error. But @classmethod is a decorator, then it returns a function, why can it be called directly by class?