객체 및 클래스 구현

매일 공부(ML)·2022년 3월 3일
0

클래스(Class)와 객체(Object)

다음은 PartAnimal 클래스입니다. 여기에서 an이라는 객체를 만들어서 party 메소드를 3번 실행시키면 다음과 같은 결과가 출력됩니다.


class PartyAnimal:
    x = 0

    def party(self) :
        self.x = self.x + 1
        print("So far",self.x)

an = PartyAnimal()

an.party()
an.party()
an.party()

# So far 1
# So far 2
# So far 3

dir()과 type()

dir 함수와 type 함수를 사용하면 객체를 검사할 수 있습니다.

x라는 리스트를 만든 후 dir(x)라고 실행하면 다음과 같은 결과를 확인할 수 있습니다.

x = list()
dir(x)

'''
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
'''

여기에서 ''로 시작해서 ''로 끝나는 것들에 대한 설명은 생략하겠지만 그 아래에 있는 것들은 그동안 우리가 사용해왔던 메소드들입니다.

각 객체에 dir 함수를 실행시키면 해당 객체에서 사용 가능한 메소드와 기본으로 포함되는 변수들을 알 수 있습니다.

x는 리스트 객체이기 때문에 append, sort 등의 메소드를 실행시킬 수 있다는 것을 알 수 있습니다.

type 함수에 x 객체를 넣으면 x가 어떤 클래스에 속한 객체인지를 알 수 있습니다.

다음 코드에서는 x가 리스트의 객체라는 것을 우리에게 알려줍니다.


print(type(x))

# <class 'list'>

이번엔 우리가 직접 만든 클래스의 객체에 대해 다음과 같이 실행해보겠습니다.


class PartyAnimal:
    x = 0

    def party(self) :
        self.x = self.x + 1
        print("So far",self.x)

an = PartyAnimal()

print("Type", type(an))
print("Dir ", dir(an))

# Type <class '__main__.PartyAnimal'>
# Dir  ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', 
# '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
# '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 
# 'party', 'x']

이렇게 type 함수를 통해 an이라는 객체는 PartyAnimal 클래스의 객체라는 것을 알 수 있고 dir 함수를 통해 an 객체에는 party라는 메소드와 x라는 변수가 포함되어있다는 사실을 알 수 있습니다.

profile
성장을 도울 아카이빙 블로그

0개의 댓글