본문 바로가기

교육/Python 0309-0313

04. 클래스

자기자신을 가리킬 때

self 지시어를 사용함


self 는 클래스 함수 선언 시 파라미터로 self를 사용해야한함

이러한 함수는 호출 시 self 호출하지 않아도 됨.

인스턴스랑 self는 주소가 같음


클래스멤버변수 선언은 생략가능.

self. 으로 인해 멤버변수 선언과 동일한 역할을 함.


생성자는 __init__ 함수 정의함으로써 수행가능


class Test:

    def __init__(self, x=0, y=0):

        print('init call')

        self._a = x

        self._b = y

        

    def SetData(self, x, y):

        self._a = x

        self._b = y

        print(id(self))

    

    def Show(self):

        print("_a=",self._a, "_b=",self._b)

        print(id(self))

        

    def StaticFn():

        print('start staticFn')


    def __del__(self):

        print('destructor call')


def Fn():

    obj = Test(5, 5)

    obj.SetData(10, 20)

    obj.Show()

    print(id(obj))

    print("_a=",obj._a, "_b=",obj._b)

    

    obj1 = Test()

    obj1.SetData(10, 20)

    obj1.Show()

    print(id(obj1))

    

    print(isinstance(obj1, Test))


if __name__ == '__main__':

    Fn()

    Test.StaticFn()

    print('hello')



Property 메소드 생성하는 경우

Get property
@property


Set property 

@변수명.setter


또는 


변수명 = property(fget=None, fset=None, fdel=None, doc=None)

ex) price = property(get_price, set_price)

fget = get 함수

fset = set 함수

fdel = delete 함수

doc = 속성 설명 함수


class Calendar:

    _month = 0

    @property

    def month(self):

        print('get call')

        return self._month

    

    @month.setter

    def month(self, value):

        print('set call', value)

        self._month = value

        

if __name__ == '__main__':

    obj = Calendar()

    obj.month = 100

    print(obj.month)




class 안에서 static 변수 혹은 함수를 생성하는 경우

@staticmethod


'교육 > Python 0309-0313' 카테고리의 다른 글

06. 예외처리  (0) 2015.03.11
05. 상속  (0) 2015.03.11
04. 함수  (0) 2015.03.10
03. 흐름제어  (0) 2015.03.09
02. 연산자  (0) 2015.03.09