Python understanding of self CLS decorator

  • 2020-04-02 09:19:16
  • OfStack

1. Self, CLS is not a keyword
In python, self, CLS is not a keyword, so you can use any variable you write to do the same thing
Code 1

class MyTest: 
myname = 'peter' 
def sayhello(hello): 
print "say hello to %s" % hello.myname 

if __name__ == "__main__": 
MyTest().sayhello() 

In code 1, you replace self with hello, and you get the same result. You can also replace it with this, which is commonly used in Java.
Conclusion: self and CLS are just conventions in python and are essentially function arguments with no particular meaning.
Any object that calls a method passes itself into the function as the first argument in the method. (since everything is an object in python, when we use class.method (), the first argument is actually the CLS we've agreed upon.)
2. Class definitions can be changed dynamically
Code 2

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 variable and function definitions in the MyTest class have been modified, and the instantiated instance has different behavior characteristics.
3. The decorator
The decorator is a function that takes a function as an argument and returns a function
Code 3
 
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 popular @classmethod for example
The normal way to use it is
Code 4

class C: 
@classmethod 
def foo(cls, y): 
print "classmethod", cls, y 

Here's the catch: if a method doesn't use @classmethod, then class.method () will give you an error. But @classmethod is a decorator, so it also returns a function, so why is it called directly by Class?

Related articles: