클래스 생성자, 소멸자 등 특수한 형태의 __메서드__(더블 언더스코어 메서드)를 이용하여 보다 더 객체스러운 클래스를 공부했다. 



================================== Python ==================================

class Song:

    def set(self, name):

        self.value = name

    def get(self):

        return self.value


c = Song()

c.set('홍길동')

print(c.get())  # 결과는 홍길동.

print(c.value)  # 결과는 홍길동.



class Song:

    def set(self, name):

        self._value = name

    def get(self):

        return self._value


c = Song()

c.set('홍길동')

print(c.get())  # 결과는 홍길동.

print(c.value)  # 결과는 홍길동.



class Song:

    def set(self, name):

        self.__name = name

    def get(self):

        return self.__name


c = Song()

c.set('홍길동')

print(c.get())  # 얘는 출력

print(c.__name)  # 얘는 오류가 난다.  AttributeError: 'Song' object has no attribute '__name'



class Song:

    def set(self, name):

        self.name = name

    def get(self):

        return self.name

c = Song()

Song.set('홍길동')  # 오류 발생. TypeError: set() missing 1 required positional argument: 'name'

    # Song.set(a, '홍길동')  # 오류 발생. NameError: name 'a' is not defined



class Song:

    def set(self, name):

        self.name = name

    def get(self):

        return self.name


c = Song()


Song.set(c, '홍길동')  # 생성자를 넣어줘서 클래스 호출

print(Song.get(c))  # 결과는 홍길동.

print(Song.get())  # 오류 발생. TypeError: get() missing 1 required positional argument: 'self'



class MethodClass:

    def set(self, name):

        self.value = name

    def add(self):

        self.set(self.value + ' 전우치')

    def get(self):

        return self.value

c = MethodClass()

c.set('홍길동')  # value = '홍길동'

c.add()  # value = '홍길동 전우치'

print(c.get())  # 결과는 홍길동 전우치.




class StringCall:

    def __repr__(self):  # 오버라이드 된다.

        '''

        객체를 대표하여 유일하게 표현할 수 있는 공식적인 문자열이다.

        eval 내장함수에 의하여 같은 객체로 재생성 될 수 있는 문자열 표현이다

        '''

        return '공식적인 문자열'

    def __str__(self):   # java의 toString(). 오버라이드 된다.

        '''

        객체의 비공식적인 문자열이며 일반적으로 가장 많이 사용한다.

        사용자가 보기 편한 형태로 자유롭게 표현될 수 있는 문자열 표현이다.

        '''

        return '비공식적인 문자열'

s = StringCall()

print(s)



def call_check(no_call):

    if callable(no_call):

        print('호출 가능')

    else:

        print('호출 불가능')


class A:

    def __call__(self, other):

        return other


class B:

    def no_call(self, other):

        return other


a = A()

b = B()

call_check(a)  # 결과는 호출 가능

call_check(b)  # 결과는 호출 불가능.



import time

class Life:

    def __init__(self):   # 생성자.

        print('현재시간 : ', time.ctime())

call = Life()

time.sleep(5)

print('5초가 지났습니다.', time.ctime())


class Life:

    def __init__(self,integer):

        self.integer = integer

    def __str__(self):

        return str(self.integer)


call = Life(10)

print(call)  # __str__가 없으면 나오는 값. <__main__.Life object at 0x000000A454C10B00>

             # __str__이 있으면 10이 출력된다.



class Life:

    def __init__(self,integer):

        self.public = 10

        self._private = '홍길동'

    def _private(self):

        print(self.public)

        print(self._private)


call = Life(10)

print(call)



class Life:

    def __init__(self):

        self.public = 10

        self._private = '홍길동'

    def _privatecall(self):

        print(self.public)

        print(self._private)

    #def __str__(self):

        #return 'public : ' + str(self.public) + ', _private : ' + str(self._private)


call = Life()

call._privatecall()

'''

'결과'

10

홍길동

'''



from time import ctime

class LifeClass:

    def __init__(self):

        print('현재 시간: ', ctime( ))

    def __del__(self):   # 소멸시 사용된다.

        print('소멸 시간: ', ctime( ))

calltime = LifeClass( )

calltime

'''

'결과'

현재 시간:  Mon Jun  4 10:35:17 2018

소멸 시간:  Mon Jun  4 10:35:17 2018

'''



class Song:

    def __init__(self, end):

        self.end = end

    def __len__(self):

        return self.end

    def __getitem__(self, item):

        if item < 0 or self.end <= item:

            raise IndexError(item)

        return item * item

call = Song(10)

for i in call:

    print(i, end=' ')




class Song:

    def __init__(self, dict = None):

        if dict == None:

            dict = {}

        self.dict = dict

    def __setitem__(self, key, value):

        self.dict[key] = value

    def __getitem__(self, item):

        return self.dict[item]


call = Song()

call['name'] = '홍길동'

call['age'] = 33

print(call['name'])

print(call['age'])



class SuperClass:

    def __init__(self):

        print('슈퍼 클래스 호출')

class SubClass(SuperClass):  # SubClass는 SuperClass를 상속받았다. SuperClass가 부모, SubClass가 자식

    def __init__(self):

        SuperClass.__init__(self)

        print('서브 클래스 호출')


a = SuperClass()

a  # 슈퍼 클래스 호출

b = SubClass()

b  # 슈퍼 클래스 호출l 서브 클래스 호출


================================== Python ==================================

+ Recent posts