[파이썬] Class

^_^·2022년 5월 26일
0

Python

목록 보기
1/9
post-thumbnail

클래스

클래스는 객체를 표현하기 위한 문법이다. 우리가 변수와 함수를 사용해 코딩을 한다고 가정하면 각 변수와 함수를 입력해야 한다. 변수와 함수가 많지 않다면 하나하나 코딩을 하면 되겠지만 많이 만들어야 한다면 쉬운일이 아니다. 이럴 때 클래스를 사용하면 여러 변수와 함수를 만들지 않고도 사용할 수 있다. 실제 코드를 보자 아래 두 코드는 노트북의 색, 성능, 가격을 클래스를 나타내는데 클래스를 사용하지 않는 방법과 클래스를 사용한 방법이다

각각의 노트북의 종류를 변수로 지정하고 세부사항을 리스트 내의 딕셔너리로 만들었다. 만약 노트북의 수가 많아지면 하나하나 추가해 많은 변수를 만들어야 하는 상황이 생긴다.


laptop_1 = 'Gram'
laptop_detail_1 = [
    {'color' : 'White'},
    {'ram' : 16},
    {'price' : 1700000}
]

laptop_2 = 'Macbook'
laptop_detail_2 = [
    {'color' : 'Silver'},
    {'ram' : 8},
    {'price' : 1500000}
]

laptop_3 = 'Thinkpad'
laptop_detail_3 = [
    {'color' : 'Black'},
    {'ram' : 16},
    {'price' : 1400000}
]

아래 두 코드는 리스트와 딕셔너리로 노트북의 종류와 세부사항을 만들었다. Macboook의 정보를 제외한 나머지 노트북의 정보를 알기위해 리스트의 요소를 삭제하고 출력했다.


laptop_list = ['Gram', 'Macbook', 'Thinkpad']
laptop_detail_list = [
    	{'color' : 'White', 'ram' : 16, 'price' : 1700000},
        {'color' : 'Silver', 'ram' : 8, 'price' : 1500000},
        {'color' : 'Black', 'ram' : 16, 'price' : 1400000}
]

del laptop_list[1]
del laptop_detail_list[1]

print(laptop_list)
print(laptop_detail_list)

# 출력 결과
['Gram', 'Thinkpad']
[{'color': 'White', 'ram': 16, 'price': 1700000}, {'color': 'Black', 'ram': 16, 'price': 1400000}]

laptop_dicts = [
    {'laptop' : 'Gram', 'laptop_detail' : {'color' : 'White', 'ram' : 16, 'price' : 1700000}},
    {'laptop' : 'Macbook', 'laptop_detail' : {'color' : 'Silver', 'ram' : 8, 'price' : 1500000}},
    {'laptop' : 'Thinkpad', 'laptop_detail' : {'color' : 'Black', 'ram' : 16, 'price' : 1400000}}
]

del laptop_dicts[1]
print(laptop_dicts)

# 출력결과

[{'laptop': 'Gram', 'laptop_detail': {'color': 'White', 'ram': 16, 'price': 1700000}}, 
{'laptop': 'Thinkpad', 'laptop_detail': {'color': 'Black', 'ram': 16, 'price': 1400000}}]

이번에는 class를 사용해 노트북의 종류와 세부정보를 가져와보자. class를 사용할때는 __init__ 이라는 메소드를 사용하는데 이 메소드는 생성자로 객체에 초깃값을 설정할 때 사용한다. 생성자(Constructor)란 객체가 생성될 때 자동으로 호출되는 메서드를 의미한다. __init__의 첫번째 인자는 self를 사용해야 하는데 여기서 self는
__str__은 파이썬 내장 함수로 문자열 출력을 할때 사용한다. __str__를 사용하지 않고 출력하면 메모리 주소가 출력되기 때문에 입력해 주었다.
class를 만들었으면 클래스를 사용할 인스턴스를 생성해야 한다. 인스턴스 안에 노트북의 이름과 세부정보를 넣어준다.

클래스로 만든 객체를 인스턴스라고도 한다. a = Laptop() 이렇게 만든 a는 객체이다. 그리고 a 객체는 Laptop의 인스턴스이다.


class Laptop():
    def __init__(self, laptop, details):
        self._laptop = laptop
        self._details = details

    def __str__(self):
        return '{} - {}'.format(self._laptop, self._details)

# 인스턴스 생성
laptop1 = Laptop('Gram',{'color' : 'White', 'rma' : 16, 'price' : 1700000})
laptop2 = Laptop('Macbook',{'color' : 'Silver', 'rma' : 8, 'price' : 1500000})
laptop3 = Laptop('Thinkpad',{'color' : 'Black', 'rma' : 16, 'price' : 1400000})

print(laptop1)
print(laptop2)
print(laptop3)

# 출력 결과

Gram - {'color': 'White', 'rma': 16, 'price': 1700000}
Macbook - {'color': 'Silver', 'rma': 8, 'price': 1500000}
Thinkpad - {'color': 'Black', 'rma': 16, 'price': 1400000}

이제 클래스를 사용해 노트북과 세부정보를 구할 수 있게 되었다. 다른 노트북이 추가 된다면 인스턴스를 추가하여 구할 수 있다. 그런데 위의 과정까지는 클래스의 장점이 딱히 보이지 않는다. 위 코드에 함수를 추가해 구해야할 정보를 추가해보면 다르게 느껴질 것이다. 인스턴스 메소드를 추가해 가격인상전과 후를 출력해보자. 물가 상승으로 인한 가격 인상을 코드로 표현하기 위해 클래스 변수로 기본 인상률을 1로 지정했다. 클래스 변수는 클래스 내에 있기 떄문에 모든 인스턴스가 공유한다.

그리고 인스턴스 메소드를 사용했는데 인스턴스 메소드는 첫번째 인자로 self를 받는 메소드이다. 이메소드를 이용해 물가상승 전과 후의 노트북 가격을 확인했다.

인스턴스 메소드의 인자는 self외에 여러개가 될 수 있고, 클래스로 인스턴스를 생성한 후에 사용할 수 있다. 인스턴스 자신을 self로 전달해 코드를 수행하고 인스턴스를 통해서 호출이 된다.


class Laptop():
    price_per_raise = 1.0

    def __init__(self, laptop, details):
        self._laptop = laptop
        self._details = details

    def __str__(self):
        return '{} - {}'.format(self._laptop, self._details)

    # Instance method
    def get_price(self):
        return 'Before Car Price -> laptop : {}, price : {}'.format(self._laptop, self._details.get('price'))

    # Instance method
    def get_price_culc(self):
        return 'After Car Price -> laptop : {}, price : {}'.format(self._laptop, self._details.get('price')* Laptop.price_per_raise)

# 인스턴스 생성
laptop1 = Laptop('Gram',{'color' : 'White', 'rma' : 16, 'price' : 1700000})
laptop2 = Laptop('Macbook',{'color' : 'Silver', 'rma' : 8, 'price' : 1500000})
laptop3 = Laptop('Thinkpad',{'color' : 'Black', 'rma' : 16, 'price' : 1400000})

print(laptop1)
print(laptop2)
print(laptop3)

# 가격정보(인상 전)
print(laptop1.get_price())
print(laptop2.get_price())
print(laptop3.get_price())


# 가격 인상(클래스 메소드 미사용) 직접 접근하는 방법(좋지않음)
Laptop.price_per_raise = 1.5

# 가격정보(인상 후)
print(laptop1.get_price_culc())
print(laptop2.get_price_culc())
print(laptop3.get_price_culc())


# 출력 결과

Gram - {'color': 'White', 'rma': 16, 'price': 1700000}
Macbook - {'color': 'Silver', 'rma': 8, 'price': 1500000}
Thinkpad - {'color': 'Black', 'rma': 16, 'price': 1400000}
Before Car Price -> laptop : Gram, price : 1700000
Before Car Price -> laptop : Macbook, price : 1500000
Before Car Price -> laptop : Thinkpad, price : 1400000
After Car Price -> laptop : Gram, price : 2550000.0
After Car Price -> laptop : Macbook, price : 2250000.0
After Car Price -> laptop : Thinkpad, price : 2100000.0

이렇게 클래스를 사용해 인스턴스를 생성하면 클래스 내의 메소드를 통해 코드를 여러번 치지 않고도 원하는 결과를 얻을 수 있다.

0개의 댓글