so woon!

python_12일차 본문

Python/개념정리

python_12일차

xowoony 2022. 8. 12. 21:43
## 생성자 (constructor) ##
    객체에 초기값을 설정해야 할 필요가 있을 때 사용
    객체가 생성될 때 자동으로 호출되는 메서드
    __init__  사용

    스페셜메서드(매직메서드) : 파이썬에서 자동으로 호출해주는 메서드
                            앞뒤로 __가 붙은 메서드

    <형식>
    class 클래스이름:
        def __init__(self):   #생성자   #중요함
            self.속성 = 값






print('============실행결과===============')

# ex)
class Candy1:   #클래스 정의
    def set_info(self, shape, color):    #인스턴스 메서드 정의
        self.shape = shape
        self.color = color   #self.color에는 color라는 매개변수를


satang1 = Candy1()        #객체(인스턴스) 생성   #1번방법.만들고 밑에 호출함
satang1.set_info('circle', 'brown')   #인스턴스 메서드 호출 circle은 shape에 들어감, shape은 self.shape에 들어감
print(satang1.shape)
print(satang1.color)
print()

print('---------------생성자----------------')

class Candy2:    #클래스 정의
    def __init__(self, shape, color):   #생성자
        self.shape = shape
        self.color = color
satang2 = Candy2('triangle', 'red')  #2번방법. 만들자마자 호출하는 법 #객체 생성과 동시에 생성자를 호출
print(satang2.shape)
print(satang2.color)
print()


satang3 = Candy2('circle', 'pink')   #객체 생성과 동시에 생성자를 호출
print(satang3.shape)
print(satang3.color)
============실행결과===============
circle
brown

---------------생성자----------------
triangle
red

circle
pink








## 276page)
class USB:   #클래스 정의
    def __init__(self, capacity):   #생성자
        self.capacity = capacity

    def info(self):     #인스턴스 메서드 정의
        print('{}GB USB'.format(self.capacity))

usb = USB(64)   #객체(인스턴스) 생성
usb.info()     #인스턴스 메서드 호출

usb2 = USB(128)    #객체(인스턴스)생성
usb2.info()        #인스턴스 메서드 호출
============실행결과===============
64GB USB
128GB USB









## 277page)
class Service:   #클래스 정의
    def __init__(self, service):    #생성자
        self.service = service
        print('{} Service가 시작되었습니다.'.format(self.service))

    def __del__(self):    #소멸자
        print('{} Service가 종료되었습니다.'.format(self.service))

s = Service('길 안내')   #객체(인스턴스) 생성    => 생성자가 실행됨
del s                    #객체(인스턴스) 삭제   => 소멸자가 실행됨
============실행결과===============
길 안내 Service가 시작되었습니다.
길 안내 Service가 종료되었습니다.








## 클래스 변수 ##
    클래스 안에서 공간이 할당된 변수
    여러 인스턴스(객체)가 클래스 변수 공간을 함께 사용






## 클래스 메서드##
    클래스 변수를 사용하는 메서드
    인스턴스 없어도 호출 가능
    매개변수 cls 사용
    @classmethod  데코레이터로 표시







## ex)
class Car:   #클래스 정의
    count = 0    # 클래스 변수

    def __init__(self, name, speed):   #생성자
        self.name = name   #인스턴스 변수
        self.speed = speed   #인스턴스 변수
        Car.count += 1       #클래스 변수에 1씩 증가   원래 0이었는데 1이 증가하여 1이됨

my_car = Car('붕붕카', 0)
print(f'{my_car.name}의 현재 속도 : {my_car.speed}km, 생산된 자동차 수 : {Car.count}대')

bro_car = Car('빵빵카', 30)   #객체(인스턴스) 생성
print(f'{bro_car.name}의 현재 속도 : {bro_car.speed}km, 생산된 자동차 수 : {Car.count}대')

sis_car = Car('띠띠카', 60)   #객체(인스턴스) 생성
print(f'{sis_car.name}의 현재 속도 : {sis_car.speed}km, 생산된 자동차 수 : {Car.count}대')






#ex)
class Korean:    #클래스 정의
    country = '한국'    #클래스 변수

    @classmethod
    def trip(cls, country):    #클래스 메서드 정의
        if cls.country == country:
            print('국내여행입니다!')
        else:
            print('해외여행입니다!')

Korean.trip('한국')            #객체없이 호출 가능(클래스 메서드의 특징)
     #한국이 country로 들어감, cls.country는 한국임  둘다 같으므로 국내여행입니다! 가 나옴
Korean.trip('미국')
============실행결과===============
붕붕카의 현재 속도 : 0km, 생산된 자동차 수 : 1대
빵빵카의 현재 속도 : 30km, 생산된 자동차 수 : 2대
띠띠카의 현재 속도 : 60km, 생산된 자동차 수 : 3대
국내여행입니다!
해외여행입니다!









print('============실행결과===============')

## 282page)
class Bag:    #클래스 정의
    count = 0     #가방 개수(클래스 변수)

    def __init__(self):    #생성자
        Bag.count += 1     #생성자 호출될 때마다 1씩 증가하겠다라는 뜻

    @classmethod
    def sell(cls):    #클래스 메서드 정의
        cls.count -= 1   #호출될 때마다 1씩 감소

    @classmethod
    def remain_bag(cls):    #클래스 메서드 정의
        return cls.count      #가방 개수를 알려줌

print('현재 가방 : {}개'.format(Bag.remain_bag()))
bag1 = Bag()    #인스턴스(객체) 생성
bag2 = Bag()
bag3 = Bag()
print('현재 가방 : {}개'.format(Bag.remain_bag()))
bag1.sell()   #Bag,sell() 해도 됨
bag2.sell()
print('현재 가방 : {}개'.format(Bag.remain_bag()))
============실행결과===============
현재 가방 : 0개
현재 가방 : 3개
현재 가방 : 1개






## 클래스 상속 ##
# ex)
class Person:   #슈퍼클래스(부모클래스)
    def __init__(self, name):   #생성자
        self.name = name

    def eat(self, food):   #인스턴스 메서드
        print(f'{self.name}가 {food}를 먹습니다.')

class Student(Person):    #서브클래스(자식클래스)   자식(부모)
    def __init__(self, name, school):   #생성자
        super().__init__(name)   #슈퍼(부모) 클래스의 생성자 호출
        self.school = school

    def study(self):    #인스턴스 메서드
        print(f'{self.name}는 {self.school}에서 공부를 합니다!')

potter = Student('해리포터', '호그와트')        #객체(인스턴스) 생성
potter.eat('감자')    #상속받은 메서드 호출
potter.study()    #인스턴스 메서드 호출
============실행결과===============
해리포터가 감자를 먹습니다.
해리포터는 호그와트에서 공부를 합니다!







## 286 page)

class Coffee:    #슈퍼클래스(부모클래스)
    def __init__(self, bean):   #생성자
        self.bean = bean

    def coffee_info(self):    #인스턴스 메서드 정의
        print('원두 : {}'.format(self.bean))

class Espresso(Coffee):     #서브클래스(자식클래스)
    def __init__(self, bean, water):   #생성자
        super().__init__(bean)    #부모의 생성자를 호출
        self.water = water

    def espresso_info(self):     #인스턴스 메서드 정의
        super().coffee_info()    #부모 클래스의 메서드를 호출
        print('물 : {}ml'.format(self.water))

coffee = Espresso('콜롬비아', 30)    #객체 (인스턴스) 생성
coffee.espresso_info()    #인스턴스 메서드 호출

coffee2 = Espresso('예가체프', 50)   #객체(인스턴스)생성
coffee2.espresso_info()

coffee3 = Espresso('맥심모카골드', 60)  # 객체(인스턴스) 생성
coffee3.espresso_info()
============실행결과===============
원두 : 콜롬비아
물 : 30ml
원두 : 예가체프
물 : 50ml
원두 : 맥심모카골드
물 : 60ml









## 파일 입출력의 활용 ##
## 파일 복사 ##
buffer_size = 1024  #한번에 읽어들이는 데이터의 크기(1kb==1024byte)
with open('code.mp4', 'rb') as source:  #동영상을 바이너리 모드로 읽는다
                                        # b = 동영상, 소리, 그림은 바이너리 모드
    with open('code2.mp4', 'wb') as copy:    #복사할 동영상을 바이너리 모드로 쓴다.
        while True:
            buffer = source.read(buffer_size)
            if not buffer:   #버퍼의 내용이 아무것도 없다면
                break     #중지
            copy.write(buffer)  #buffer의 내용을 복사할 파일에 기록

print('code2.mp4 파일이 복사되었습니다.')   #파일에 code2 동영상이 생성됨
============실행결과===============
code2.mp4 파일이 복사되었습니다.

'Python > 개념정리' 카테고리의 다른 글

python_14일차  (0) 2022.08.22
python_13일차  (0) 2022.08.17
python_11일차  (0) 2022.08.10
python_10일차  (0) 2022.08.10
python_9일차  (0) 2022.08.10
Comments