Sabtu, 13 Desember 2025

Staticmethod dan Classmethod pemrograman python

class Hero:

    # private class variable
    __jumlah = 0

    def __init__(self, name):
        self.name = name
        Hero.__jumlah += 1

    # method ini hanya berlaku untuk object
    def getJumlah(self):
        return Hero.__jumlah
   
    # method ini tidak berlaku untuk object
    def getJumlah1():
        return Hero.__jumlah
   
    # method static (decorator)
    @staticmethod
    def getJumlah2():
        return Hero.__jumlah

    @classmethod
    def getJumlah3(cls):
        return cls.__jumlah
   
sniper = Hero("Sniper")
print (Hero.getJumlah2())
archer = Hero("Archer")
print (sniper.getJumlah2())
sword = Hero("sword")
print (Hero.getJumlah3())


Tidak ada komentar:

Posting Komentar