Instance Methods

Class Methods

Static Methods

Example

class A(object):def foo(self,x):print "executing foo(%s,%s)"%(self,x)@classmethoddef class_foo(cls,x):print "executing class_foo(%s,%s)"%(cls,x)@staticmethoddef static_foo(x):print "executing static_foo(%s)"%xa=A()
>>> obj = MyClass()>>> obj.method()('instance method called', <MyClass instance at 0x101a2f4c8>)>>> MyClass.method(obj)  # 이런 식으로 instance를 넣어서 사용하는 것도 가능.('instance method called', <MyClass instance at 0x101a2f4c8>)>>> obj.classmethod()('class method called', <class MyClass at 0x101a2f4c8>)>>> obj.staticmethod()'static method called'

다음은 classmethod 를 생성자로 사용하는 간단한 예제입니다.

# -*- coding: utf-8 -*-class Person(object):my_class_var = 'sanghee'def __init__(self, year, month, day, sex):self.year = yearself.month = monthself.day = dayself.sex = sexdef __str__(self):return '{}년 {}월 {}일생 {}입니다.'.format(self.year, self.month, self.day, self.sex)@classmethoddef ssn_constructor(cls, ssn):front, back = ssn.split('-')sex = back[0]if sex == '1' or sex == '2':year = '19' + front[:2]else:year = '20' + front[:2]if (int(sex) % 2) == 0:sex = '여성'else:sex = '남성'month = front[2:4]day = front[4:6]return cls(year, month, day, sex)@staticmethoddef is_work_day(day):# weekday() 함수의 리턴값은# 월: 0, 화: 1, 수: 2, 목: 3, 금: 4, 토: 5, 일: 6if day.weekday() == 5 or day.weekday() == 6:return Falsereturn Truessn_1 = '900829-1034356'ssn_2 = '051224-4061569'person_1 = Person.ssn_constructor(ssn_1)print(person_1)person_2 = Person.ssn_constructor(ssn_2)print(person_2)import datetime# 일요일 날짜 오브젝트 생성my_date = datetime.date(2016, 10, 9)# 클래스를 통하여 스태틱 메소드 호출print(Person.is_work_day(my_date))# 인스턴스를 통하여 스태틱 메소드 호출print(person_1.is_work_day(my_date))>>> 1990년 08월 29일생 남성입니다.>>> 2005년 12월 24일생 여성입니다.>>> False>>> False

Reference