CKTIS / Python
classmethod()
Ob dostopu do metode kot prvi argument veže razred, tudi pri dostopu prek primerka.
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
@classmethod
def make(cls):
return cls()Ob dostopu do metode kot prvi argument veže razred, tudi pri dostopu prek primerka.
Ime cls je dogovor. Square podeduje make iz Shape, vendar Square.make poda Square.
Zato cls() ustvari objekt Square in program izpiše 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
Primeri
class Shape:
@classmethod
def make(cls):
return cls()
class Square(Shape):
pass
print(type(Square.make()).__name__)
Rezultat
Square
Zato cls() ustvari objekt Square in program izpiše to ime tipa.