Python-b02-classmethod-staticmethod

This article shows the examples of classmethod and staticmethod in python

regular method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Employee:
raise_amount = 2.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)

def set_regular_raise_amount(self, amount):
self.raise_amount = amount


emp_1 = Employee('Bob', 'Gobdo', 20)
emp_2 = Employee('John', 'Youh', 30)

emp_1.set_regular_raise_amount(6)

print(emp_1.raise_amount) # 6
print(emp_2.raise_amount) # 2.04
print(Employee.raise_amount) # 2.04
```
## classmethod

class Employee:
raise_amount = 2.04

def __init__(self, first, last, pay):
    self.first = first
    self.last = last
    self.pay = pay
    self.email = first + '.' + last + '@company.com'

def fullname(self):
    return '{} {}'.format(self.first, self.last)

def apply_raise(self):
    self.pay = int(self.pay * self.raise_amount)

def set_regular_raise_amount(self, amount):
    self.raise_amount = amount

@classmethod
def set_class_raise_amount(cls, amount):
    cls.raise_amount = amount

emp_1 = Employee(‘Bob’, ‘Gobdo’, 20)
emp_2 = Employee(‘John’, ‘Youh’, 30)

Employee.set_class_raise_amount(5)

print(emp_1.raise_amount) # 5
print(emp_2.raise_amount) # 5
print(Employee.raise_amount) # 5

1
## staticmethod

class Employee:
raise_amount = 2.04

def __init__(self, first, last, pay):
    self.first = first
    self.last = last
    self.pay = pay
    self.email = first + '.' + last + '@company.com'

def fullname(self):
    return '{} {}'.format(self.first, self.last)

def apply_raise(self):
    self.pay = int(self.pay * self.raise_amount)

def set_regular_raise_amount(self, amount):
    self.raise_amount = amount

@classmethod
def set_class_raise_amount(cls, amount):
    cls.raise_amount = amount

@staticmethod
def is_workday(day):
    if day.weekday() == 5 or day.weekday() == 6:
        return False
    return True

import datetime
my_date = datetime.date(2016,1,2)
print(Employee.is_workday(my_date)) # False

1
## example

class A(object):
bar = 1

def func1(self):
    print('foo')

@classmethod
def func2(cls):
    print('func2')
    print(cls.bar)
    cls().func1()

@staticmethod
def func3():
    print('func3')
    print(A.bar)

A().func1() # foo
A.func2() # func2
# 1
# foo
A.func3() # func3
# 1

```