The last article introduced what is python Medium self, Please refer to :
Python Interview questions :self What is it
To put it simply self It's a class (Class) Instantiated object .
There is another question that is often mentioned in the interview , That's it —— What is? cls Well ?
cls It's a class ( Subclass ) In itself , Depends on which class is called .
See the following example
class MyClass1():
@classmethod
def test_cls(cls):
print(cls)
class MyClass2():
@classmethod
def test_cls(cls):
print(cls)
MyClass1.test_cls()
MyClass2.test_cls()
Output :
<class '__main__.MyClass1'>
<class '__main__.MyClass2'>
We can also call through the method of the instance class method, for example :
MyClass1.test_cls()
MyClass2.test_cls()
my1=MyClass1()
my2=MyClass2()
my1.test_cls()
my2.test_cls()
The same output
Output :
<class '__main__.MyClass1'>
<class '__main__.MyClass2'>
Use cls As a method parameter , Usually this method needs to be controlled by @classmethod modification ,@classmethod A decorated method represents a class method . Here we need to pay attention to cls It's just a sign , You can write him as abc,bcd It's all right , It was written out of habit cls.
since cls Is a class , Then we can use it to instantiate , The specific code is as follows :
class MyClass3():
@classmethod
def test_cls_obj(cls):
obj1 = cls()
obj2 = cls()
print(obj1)
print(obj2)
print(type(obj1))
print(type(obj2))
MyClass3.test_cls_obj()
Output :
<__main__.MyClass3 object at 0x000000690A1E0C08>
<__main__.MyClass3 object at 0x000000690A1E0C48>
<class '__main__.MyClass3'>
<class '__main__.MyClass3'>
You can see through obj1=cls() and obj2=cls(), Two instances were successfully created , Namely 0x000000690A1E0C08 and 0x000000690A1E0C48, The types of these two instances are MyClass3'
in addition cls You can also do it in python Methods in class __new__ To realize , Usually defined as :
class class_name:
def __new__(cls, *args, **kwargs):
return super(class_name, cls).__new__(cls, *args, **kwargs)
Next I will write an article about __new__ and __init__ , Please keep your eyes on !
Finally, we can briefly summarize self and cls: To put it simply self It's a class (Class) Instantiated object .
cls It's a class ( Subclass ) In itself . We can also easily understand self That represents an instance ,cls Represents the !