마케팅/데이터분석(파이썬)

(파이썬/python) 모두를 위한 프로그래밍 : 파이썬 챕터 14 / 파이썬 객체

마케터 조쉬 2021. 11. 27. 03:43

파이썬 객체

클래스 : 쿠키 틀

객체 : 쿠키

애트리뷰션 : 쿠키의 속성

 

클래스와 객체

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()
print(dir(x))

['__add__', '__class__', '__class_getitem__', '__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 함수를 실행시키면 해당 객체에서 사용가능한 메소드와 기본으로 포함되는 변수들을 알 수 있습니다.

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, [위와 같음, 'party', 'x]
#party 메소드와 x라는 변수가 포함되어 있음을 알 수 있다.

 

생성자와 소멸자

파이썬의 생성자는 __init__, 소멸자는 __del__로 정의합니다.

이 코드에서는 객체를 생성할 때 생성자가 실행이 되고, 객체가 사라질 때 소멸자가 실행되는 것을 볼 수 있습니다.

class PartyAnimal:
    x = 0
    
    def __init__(self):
        print('I am constructed')
    
    def party(self) :
        self.x=self.x+1
        print("So far", self.x)
    
    def __del__(self):
        print('I am destructed', self.x)
        
an = PartyAnimal()
an.party()
an.party()
an = 42
print('an contains', an)

#I am constructed
#So far 1
#So far 2
#I am destructed 2
#an contains 42

#객체를 생성할 때 이름을 매개 변수로 넣어 name이라는 속성에 저장을 합니다.

class PartyAnimal:
    x = 0
    name = ""
    def __init__(self,z):
        self.name = z
        print(self.name, "constructed")
    
    def party(self) :
        self.x=self.x+1
        print(self.name,"party count",self.x)
            
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")

s.party()
j.party()
s.party()

#Sally constructed
#Jim constructed
#Sally party count 1
#Jim party count 1
#Sally party count 2

 

상속

PartyAnimal 클래스의 모든 것을 상속한 FootballFan 클래스를 정의하고 각각의 객체를 생성하여 실행

class PartyAnimal:
    x = 0
    name = ""
    def __init__(self,nam):
        self.name = nam
        print(self.name, "constructed")
    
    def party(self) :
        self.x=self.x+1
        print(self.name,"party count",self.x)

class FootballFan(PartyAnimal):
    points = 0
    def touchdown(self):
        self.points = self.points + 7
        self.party()
        print(self.name,"points",self.points)
        
s = PartyAnimal("Sally")
s.party()

j = FootballFan("Jim")
j.party()
j.touchdown()

#Sally constructed
#Sally party count 1
#Jim constructed
#Jim party count 1
#Jim party count 2
#Jim points 7