CKTIS / Python
classmethod()
Wiąże jako pierwszy argument klasę używaną przy odczycie metody, także przez jej instancję.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
@classmethod
def make(cls):
return cls()Wiąże jako pierwszy argument klasę używaną przy odczycie metody, także przez jej instancję.
Nazwa cls to konwencja. Square dziedziczy make z Shape, ale Square.make przekazuje Square.
Dlatego cls() tworzy obiekt Square i taką nazwę typu wypisuje program.
class Shape:
@classmethod
def make(cls): return cls()
class Square(Shape): pass
assert type(Square.make()) is Square and type(Square().make()) is Square
Przykłady
class Shape:
@classmethod
def make(cls):
return cls()
class Square(Shape):
pass
print(type(Square.make()).__name__)
Wynik
Square
Dlatego cls() tworzy obiekt Square i taką nazwę typu wypisuje program.