程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python interview high frequency question: what exactly is CLS

編輯:Python

 

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 Definition

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.

cls Is a class

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'

cls As __new__ Parameters of

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 !

summary cls and self

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 !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved