티스토리 뷰

Python

Special Methods

techbard 2016. 5. 4. 18:30

# Class Methods


class InsCounter():

count = 0


def __init__(self, val):

self.val = val

InsCounter.count += 1


def getValue(self):

return self.val


@classmethod

def getCount(cls):

return cls.count


a = InsCounter(1)

b = InsCounter(2)

c = InsCounter(3)


for o in [a, b, c]:

print("val of obj: {}".format(o.getValue()))

print("count: {}".format(o.getCount()))


# 결과

val of obj: 1

count: 3

val of obj: 2

count: 3

val of obj: 3

count: 3


# Static Methods


class InsCounter():

count = 0


def __init__(self, val):

self.val = self.filterint(val)

InsCounter.count += 1


@staticmethod

def filterint(val):

if not isinstance(val, int):

return 0

else:

return val


a = InsCounter(1)

b = InsCounter(2)

c = InsCounter(3)


print(a.val)

print(b.val)

print(c.val)


# 결과

1

2

3


댓글
댓글쓰기 폼
공지사항
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        
글 보관함