파이썬(Python)

파이썬 Class와 Object란? (예제로 알아보기, 내장함수 확인하기)

끄적끄적아무거나 2021. 6. 29. 13:20
반응형

python 에서 class와 object 를 설명할 때 붕어빵을 비유하여 설명을 많이 한다.

 

Class는 붕어빵을 만드는 틀이고 Object는 틀에서 만들어진 붕어빵인 것이다. 

 

Class 는 변수와 함수로 구성된다. 

 


예제를 통해 이해해보기

 

코드 >> 

class parent:
    def __init__(self, father, mother):
        self.pop = father
        self.mom = mother
    def description(self, no_ch):
        self.no_children = no_ch
        print("My father is ", self.pop)
        print("My mother is ", self.mom)
        print("I have ",self.no_children,"children")

A_family = parent("James","Jane")
A_family.description(1)
print("##########")    
B_family = parent("James","Jane")
B_family.description(3)  

 

결과>>

My father is  James
My mother is  Jane
I have  1 children
##########
My father is  James
My mother is  Jane
I have  3 children

 

주석>>

코드에서 parent 라는 클래스를 만들었다. 즉, 붕어빵 틀을 만든 것이다. 이 안에는 변수와 함수를 정의할 수 있는데 초기화에 넣는 변수는 __init__ 에 넣어주면 된다. 

 

그리고 A_family, B_family 라는 두개의 object (객체) 를 만들었다. 각 각의 객체는 클래스의 self에 들어 가게 된다. 그래서 self 를 항상 정의 해야한다. 그리고 객체를 만드는 과정을 instance 라고도 하는데 이때 인자 값은 init 에서 정의한 변수를 입력 하면된다. 그리고 함수에서 정의한 변수는 함수를 사용할 때 변수 값을 입력하면 되는 것이다. 

 

class 내부에서 변수 앞에 self를 넣는 것은 A_family 인지 B_family 인지를 알려주기 위해 필요 하다.

 


클래스 내장 함수 확인하기

 

위에 코드에 연장해서 코드를 작성하겠다. 

 

코드>>

print(dir(parent))
print("##########")    
print(dir(A_family))
print("##########")  
print(type(A_family))

 

결과>>

['__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__', 'description']
##########
['__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__', 'description', 'mom', 'no_children', 'pop']
##########
<class '__main__.parent'>

 

주석>>

dir 로 내장 함수를 확인한 결과 class 와 object의 차이점은 class에서는 아직 self로 정의한 변수가 instance 를 하지 않아서 나오지 않고 객체(object)한 값은 self가 정의 되었기 때문에 변수 값들이 나온다. 

 

type을 통해서 어떤 class를 사용했는지도 확인 가능하다.

 

 

 

 

반응형