一、cls含義
python中cls代表的是類的本身,相對應的self則是類的一個實例對象。
二、cls用法
cls可以在靜態方法中使用,並通過cls()方法來實例化一個對象。
class Person(object): def __init__(self, name, age): self.name = name self.age = age print('self:', self) # 定義一個build方法,返回一個person實例對象,這個方法等價於Person()。 @classmethod def build(cls): # cls()等於Person() p = cls("Tom", 18) print('cls:', cls) return p if __name__ == '__main__': person = Person.build() print(person, person.name, person.age)
輸出結果:
