Python 3

home

Introduction to Python

davidbpython.com




Class Methods and Static Methods


instance / object methods

Instance methods are designed to read or write attributes in the instance.


class Counter:

    # a 'setter' method
    def __init__(self, val):
        self.value = val       # set the value in the instance's attribute

    # a 'getter' method
    def getval(self):
        return self.value      # read the value in the instance's attribute

    def increment(self):
        self.value = self.value + 1


a = Counter(10)






class methods

Class methods are designed to read or write attributes in the class.


class MyClass:
    instance_count = 0

    def __init__(self, letter):
        self.id = letter
        MyClass.instance_count = MyClass.instance_count + 1

    @classmethod
    def reset_instance_count(cls):
        cls.instance_count = 0

a = MyClass('alpha')
b = MyClass('beta')

print(a.instance_count)     # 2

a.reset_instance_count()

print(a.instance_count)     # 0


Ex. 14.2






static methods

Static methods do not work with instance or class, but still may belong to the class.


import datetime

class MyClass:
    instance_list = []

    def __init__(self, letter):
        self.id = letter
        formatted_time = MyClass.get_now()
        MyClass.instance_list.append((self, formatted_time))

    @staticmethod
    def get_now():
        dt = datetime.datetime.now()   # a datetime object
        ds = dt.strftime('%H:%M:%S')   # '17:06:41' (or current time)
        return ds

a = MyClass('alpha')
time.sleep(1)               # wait 1 second
b = MyClass('beta')

print(a.id)                 # 'a'
print(b.id)                 # 'b'

print(MyClass.instance_list)     # [(<MyClass>, '17:06'), (<MyClass>, '17:07')]


Ex. 14.3





[pr]