CKTIS / Python
classmethod()
Pri pristupu metodi kao prvi argument veže klasu, također preko instance.
Verzija: Python 3.14; repository image, production runtime not attested
Sintaksa
@classmethod
def make(cls):
return cls()Pri pristupu metodi kao prvi argument veže klasu, također preko instance.
Ime cls stvar je dogovora. Square nasljeđuje make iz Shape, ali Square.make predaje Square.
Zato cls() stvara objekt Square i program ispisuje to ime tipa.
class Shape:
@classmethod
def make(cls): return cls()
class Square(Shape): pass
assert type(Square.make()) is Square and type(Square().make()) is Square
Primjeri
class Shape:
@classmethod
def make(cls):
return cls()
class Square(Shape):
pass
print(type(Square.make()).__name__)
Rezultat
Square
Zato cls() stvara objekt Square i program ispisuje to ime tipa.