class A():
S_VAL = 1
def m(self, *args, **kwargs):
print('%s.m(%s,%s)' % (self.__class__.__name__, args, kwargs))
def mA(self, *args, **kwargs):
print('%s.mA(%s,%s)' % (self.__class__.__name__, args, kwargs))
@staticmethod
def s():
print('%s.c: S_VAL=%s' % (A.__name__, A.S_VAL))
@classmethod
def c(cls):
print('%s.c: S_VAL=%s' % (cls.__name__, cls.S_VAL))
class B():
S_VAL = 2
def m(self, *args, **kwargs):
print('%s.m(%s,%s)' % (self.__class__.__name__, args, kwargs))
def mB(self, *args, **kwargs):
print('%s.mB(%s,%s)' % (self.__class__.__name__, args, kwargs))
class C(A, B):
S_VAL = 3
def m(self, *args, **kwargs):
print('%s.m(%s,%s)' % (self.__class__.__name__, args, kwargs))
A.s()
A.c: S_VAL=1
C.s()
A.c: S_VAL=1
A.c()
A.c: S_VAL=1
C.c()
C.c: S_VAL=3
def get_no_of_instances(cls_obj):
return cls_obj.no_inst
class Kls(object):
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
ik1 = Kls()
ik2 = Kls()
print(get_no_of_instances(Kls))
2
def iget_no_of_instance(ins_obj):
return ins_obj.__class__.no_inst
class Kls(object):
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
ik1 = Kls()
ik2 = Kls()
print(iget_no_of_instance(ik1))
2
class Kls(object):
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
@classmethod
def get_no_of_instance(cls_obj):
return cls_obj.no_inst
ik1 = Kls()
ik2 = Kls()
print(ik1.get_no_of_instance())
print(Kls.get_no_of_instance())
2 2
IND = 'ON'
def checkind():
return (IND == 'ON')
class Kls(object):
def __init__(self,data):
self.data = data
def do_reset(self):
if checkind():
print('Reset done for:', self.data)
def set_db(self):
if checkind():
self.db = 'new db connection'
print('DB connection made for:',self.data)
ik1 = Kls(12)
ik1.do_reset()
ik1.set_db()
Reset done for: 12 DB connection made for: 12
IND = 'ON'
class Kls(object):
def __init__(self, data):
self.data = data
@staticmethod
def checkind():
return (IND == 'ON')
def do_reset(self):
if self.checkind():
print('Reset done for:', self.data)
def set_db(self):
if self.checkind():
self.db = 'New db connection'
print('DB connection made for: ', self.data)
ik1 = Kls(12)
ik1.do_reset()
ik1.set_db()
Reset done for: 12 DB connection made for: 12
class Kls(object):
def __init__(self, data):
self.data = data
def printd(self):
print(self.data)
@staticmethod
def smethod(*arg):
print('Static:', arg)
@classmethod
def cmethod(*arg):
print('Class:', arg)
ik = Kls(23)
ik.printd()
23
ik.smethod()
Static: ()
ik.cmethod()
Class: (<class '__main__.Kls'>,)
Kls.printd()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-108-3a815b87a517> in <module>() ----> 1 Kls.printd() TypeError: printd() missing 1 required positional argument: 'self'
Kls.smethod()
Static: ()
Kls.cmethod()
Class: (<class '__main__.Kls'>,)
class InstanceManager:
cnt = 0
def __init__(self):
InstanceManager.cnt += 1
def s_print_count():
print('instance count: ' + str(InstanceManager.cnt))
sprintcount = staticmethod(s_print_count)
a = InstanceManager()
InstanceManager.s_print_count()
instance count: 1
a.s_print_count()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-144-7bf01ecb219a> in <module>() ----> 1 a.s_print_count() TypeError: s_print_count() takes 0 positional arguments but 1 was given
class InstanceManager:
cnt = 0
def __init__(self):
InstanceManager.cnt += 1
def s_print_count():
print('[staticmethod] instance count : ' + str(InstanceManager.cnt))
sprintcount = staticmethod(s_print_count)
def c_print_count(cls):
print('[classmethod] instance count : ' + str(cls.cnt))
cprintcount = classmethod(c_print_count)
a = InstanceManager()
InstanceManager.sprintcount()
[staticmethod] instance count : 1
a.cprintcount()
[classmethod] instance count : 1
class InstanceManager:
cnt = 0
def __init__(self):
InstanceManager.cnt += 1
@staticmethod
def s_print_count():
print('[staticmethod] instance count : ' + str(InstanceManager.cnt))
@classmethod
def c_print_count(cls):
print('[classmethod] instance count : ' + str(cls.cnt))
a = InstanceManager()
InstanceManager.s_print_count()
[staticmethod] instance count : 1
a.c_print_count()
[classmethod] instance count : 1
class A(object):
def foo(self, x):
print('executing foo({}, {})'.format(self, x))
@classmethod
def class_foo(cls, x):
print('executing class_foo({}, {})'.format(cls, x))
@staticmethod
def static_foo(x):
print('executing static_foo({})'.format(x))
a = A()
a.foo(1)
executing foo(<__main__.A object at 0x10cd18748>, 1)
a.class_foo(1)
executing class_foo(<class '__main__.A'>, 1)
# Class 자체를 호출할 수도 있음
A.class_foo(1)
executing class_foo(<class '__main__.A'>, 1)
a.static_foo(1)
executing static_foo(1)
A.static_foo('hi')
executing static_foo(hi)
print(a.foo)
<bound method A.foo of <__main__.A object at 0x10cd18748>>
print(a.class_foo)
<bound method type.class_foo of <class '__main__.A'>>
print(a.static_foo)
<function A.static_foo at 0x10cd1f598>
class UTIL:
@staticmethod
def addtask(a, b):
return a+b
x = UTIL.addtask(1, 4)
x
5
import time
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@staticmethod
def now():
t = time.localtime()
return Date(t.tm_year, t.tm_mon, t.tm_mday)
#example
a = Date(2011, 8, 14)
a
<__main__.Date at 0x10daf1a90>
a.year
2011
a.month
8
a.day
14
b = Date.now()
b
<__main__.Date at 0x10daf1d30>
b.year
2014
b.month
10
b.day
27
class Times(object):
factor = 1
@classmethod
def mul(cls, x):
return cls.factor * x
class TwoTimes(Times):
factor = 2
x = TwoTimes.mul(4)
x
8
Times.factor
1
TwoTimes.factor
2
class A(object):
def foo(self, x):
print(self, x)
@classmethod
def class_foo(cls, x):
print(cls, x)
@staticmethod
def static_foo(x):
print(x)
a = A()
print(a.foo)
<bound method A.foo of <__main__.A object at 0x10daee6a0>>
a.foo(100)
<__main__.A object at 0x10daee6a0> 100
print(A.class_foo)
<bound method type.class_foo of <class '__main__.A'>>
A.class_foo(100)
<class '__main__.A'> 100
print(A.static_foo)
<function A.static_foo at 0x10dadae18>
A.static_foo(100)
100
class Date(object):
day = 0
month = 0
year = 0
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
string_date = '11-09-2012'
day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)
print(date1.day)
print(date1.month)
print(date1.year)
11 9 2012
type(date1)
__main__.Date
class Date(object):
day = 0
month = 0
year = 0
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, string_date.split('-'))
# cls가 Date이니 __init__로 date1이라는 instance를 만드는거네
date1 = cls(day, month, year)
print(type(date1))
return date1
date2 = Date.from_string('11-09-2012')
print(date2.day)
print(date2.month)
print(date2.year)
<class '__main__.Date'> 11 9 2012
day, month, year로 나눈다. 왜냐하면 Date라는 클래스에서 instance를 할당하기 위해서는 인자 3개가 필요하기 때문에
cls는 Date 클래스다.
cls(day, month, year) == Date(day, month, year)
date1은 Date클래스의 instance
그걸 다시 돌려준다.
from_string에서 추출하고 다시 init을 호출하기 위한 사전 작업으로 생각하면 좋겠다.
# map 함수 test
a, b = map(int, [5, 4])
print(a)
print(b)
5 4
class Date(object):
day = 0
month = 0
year = 0
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, string_date.split('-'))
# cls가 Date이니 __init__로 date1이라는 instance를 만드는거네
date1 = cls(day, month, year)
print(type(date1))
return date1
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <=12 and year <= 3999
Date.is_date_valid('11-09-2012')
True