티스토리 뷰

Python

classmethod vs. staticmethod

techbard 2016. 5. 7. 10:45

"""

from stackoverflow

http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python


To decide whether to use @staticmethod or @classmethod you have to look inside your method. 

If your method access other var/method in your class then Use @classmethod. 

On the other hand if your method does not touched any other parts of the class then 

use @staticmethod.

"""


# class method vs. static method

class P:

parent_state = 0

child_state = 0


def __init__(self):

P.parent_state += 1


@classmethod

def get_state(cls):

return "Parent: %d" % P.parent_state + '\n' + \

"Child: %d" % P.child_state + '\n'


@staticmethod

def init_state():

print("initiating...")

P.parent_state = 0

P.child_state = 0


class C(P):

def __init__(self):

P.child_state += 1


def get_state(cls):

return "Child: %d" % cls.child_state + '\n'


p1 = P()

print(p1.get_state())


c1 = C()

print(c1.get_state())


P.init_state()

print(p1.get_state())


# 결과

Parent: 1

Child: 0


Child: 1


initiating...

Parent: 0

Child: 0


# Decorators; CLASS and STATIC Methods


"""

- A class method takes the class (not instance) as argument and works with the class object

- A static method requires no argument and does not work with the class or instance (but it still belongs in the class code)

- A decorator is a processor that modifier a function

- @classmethod and @staticmethod modify the default binding that instance methods provide

"""


# staticmethod의 쓰임 - 객체 생성 전 = __init__ 에서 메쏘드를 써야하는 경우


class FilterInit():

value = 0


def __init__(self, val):

self.value = self.filter_int(val)


@staticmethod

def filter_int(value):

if not isinstance(value, int):

return 0

else:

return value


f1 = FilterInit(1)

print(f1.value)


f2 = FilterInit('a')

print(f2.value)


# 결과

1

0


댓글
댓글쓰기 폼
공지사항
Total
410,566
Today
1
Yesterday
29
«   2019/12   »
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 30 31        
글 보관함