01_Python

44_클래스

chuu_travel 2025. 1. 10. 22:02
728x90
01. 클래스의 개념
  • 객체를 만드는 도구
  • 클래스를 통해 여러 개의 객체를 만들 수 있음
  • 동일한 클래스에서도 서로 다른 값을 가진 객체가 만들어질 수 있음

 

# 계산기 예시 코드
result = 0

def cal_add(num):
    global result
    result += num
    return result

print(cal_add(3))
print(cal_add(4))
3
7

 

 

# 만약에 2대의 계산기가 필요한 상황이라면
# 별도의 변수, 별도의 함수를 만들어야함
result2 = 0

def cal_add2(num):
    global result2
    result2 += num
    return result2

 

# 위 예시를 클래스로 구현
class Calculator:
    def __init__(self):   ###생성자
        self.result = 0

    def add(self, num):
        self.result += num
        return self.result

 

cal1 = Calculator()
cal2 = Calculator()

print(cal1.add(3))
print(cal1.add(4))
print(cal2.add(5))
print(cal2.add(7))
3
7
5
12

 

 

02. 클래스의 구성
  • 클래스는 객체가 가져야 할 구성요소를 모두 가지고 있어야함
    • 객체가 가져야 할 값, 기능
      • 값: 변수(이름, 나이, 연락처, 주소 등)
      • 기능: 함수
class WaffleMachine:
    pass
# 객체    클래스()
waffle = WaffleMachine()
waffle
<__main__.WaffleMachine at 0x1b6f72e0080>

 

type(waffle)    ###어느 클래스의 객체인지 알고싶을 때
__main__.WaffleMachine

 

03. 인스턴스 변수와 인스턴스 메소드
  • 인스턴트 변수 : 클래스를 기반으로 만들어지는 모든 객체들이 각각 따로 저장하는 변수
    • 모든 인스턴스 변수는 self라는 키워드를 붙임
    • self는 자기자신을 나타내는 의미
      • 자신이 가지고 있는 속성과 기능에 접근할 때는 self.식별자 형태로 접근
  • 인스턴스 메소드 : 인스턴스 변수를 사용하는 함수
    • 인스턴스 변수값에 따라서 각 객체마다 다르게 동작
      • 첫 번째 매개변수로 self 를 추가

※인스턴스 변수를 사용하면 자연스럽게 인스턴스 메소드가 된다

 

# 예시1. Person 클래스를 정의
class Person:
    def who_am_i(self, name, age, tel, address):
        # 인스턴스 메소드 who_am_i
        # 모든 Person클래스의 객체는 who_am_i() 메소드를 호출 가능
        # self를 제외한 나머지 매개변수에 실제로 사용될 데이터가 전달

        self.name = name
        # 인스턴스 변수 name
        # = 오른쪽에 있는 name은 매개변수의 name
        # who_am_i() 메소드를 호출할 때 전달된 name이 객체의 name이 됨

        self.age = age
        self.tel = tel
        self.address = address
# 객체 boy가 생성
boy = Person()

 

boy.name
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[14], line 1
----> 1 boy.name

AttributeError: 'Person' object has no attribute 'name'

 

boy.who_am_i("john", 15, "123-1234", "seoul")
boy.name
'john'

 

boy.age
15

 

boy.tel
'123-1234'

 

boy.address
'seoul'

 

# 예시2
class Computer:
    def set_spec(self, cpu, ram, vga, ssd):
        self.cpu = cpu
        self.ram = ram
        self.vga = vga
        self.ssd = ssd

    def hardware_info(self):
        print(f"CPU = {self.cpu}")
        print(f"RAM = {self.ram}")
        print(f"VGA = {self.vga}")
        print(f"SSD = {self.ssd}")

 

desktop = Computer()
desktop.hardware_info()

 

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[22], line 1
----> 1 desktop.hardware_info()

Cell In[20], line 10, in Computer.hardware_info(self)
      9 def hardware_info(self):
---> 10     print(f"CPU = {self.cpu}")
     11     print(f"RAM = {self.ram}")
     12     print(f"VGA = {self.vga}")

AttributeError: 'Computer' object has no attribute 'cpu'

 

desktop.set_spec("i9", "128GB", "GTX3070", "1TB")

 

desktop.hardware_info()
CPU = i9
RAM = 128GB
VGA = GTX3070
SSD = 1TB

 

notebook = Computer()
notebook.set_spec("i3", "4GB", "MX300", "256GB")
notebook.hardware_info()
CPU = i3
RAM = 4GB
VGA = MX300
SSD = 256GB

 

# 예시3
class FourCal:
    def set_data(self, first, second): # 메소드의 매개변수
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second    ### result는 함수 내부에서 사용하는 지역변수/ self.first는 인스턴스변수
        return result
cal = FourCal()
cal.set_data(4, 2)

 

print(cal.first)
print(cal.second)
print(cal.add())
4
2
6

 

test_cal = FourCal()
test_cal.set_data(3, 7)
print(test_cal.first)
print(test_cal.second)
print(test_cal.add())
3
7
10

 

# 다른 객체의 영향을 받지 않고 원래의 값을 유지함
print(cal.first)
4

 

# Fourcal에 사칙연산 기능 추가
class FourCal:
    def set_data(self, first, second): # 메소드의 매개변수
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second    ### result는 함수 내부에서 사용하는 지역변수/ self.first는 인스턴스변수
        return result

    def mul(self):
        result = self.first * self.second
        return result

    def sub(self):
        result = self.first - self.second
        return result

    def div(self):
        result = self.first / self.second
        return result
cal.mul()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[42], line 1
----> 1 cal.mul()

AttributeError: 'FourCal' object has no attribute 'mul'

 

###새로운 붕어빵 기계를 만들었으므로, 새로 정의해줘야함
cal = FourCal()
cal.set_data(4, 2)
print(cal.mul())
8

 

 

04. 생성자
  • 객체가 생성될 때 자동으로 호출되는 메소드
# set_data 메소드를 실행해야만 first와 second가 생성됨
test_const = FourCal()
test_const.add()

 

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[45], line 3
      1 # set_data 메소드를 실행해야만 first와 second가 생성됨
      2 test_const = FourCal()
----> 3 test_const.add()

Cell In[39], line 8, in FourCal.add(self)
      7 def add(self):
----> 8     result = self.first + self.second    ### result는 함수 내부에서 사용하는 지역변수/ self.first는 인스턴스변수
      9     return result

AttributeError: 'FourCal' object has no attribute 'first'

 

 

# 생성자 추가하기
class FourCal:
    def __init__(self, first, second): ##생성자  // 특수한 상황에 자동으로 호출되는 메소드를 __XXX__로 표시
        # self.first = first
        # self.second = second
        self.set_data(first, second)  ##위 두줄과 같은 코드
    
    def set_data(self, first, second): # 메소드의 매개변수
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second    ### result는 함수 내부에서 사용하는 지역변수/ self.first는 인스턴스변수
        return result

    def mul(self):
        result = self.first * self.second
        return result

    def sub(self):
        result = self.first - self.second
        return result

    def div(self):
        result = self.first / self.second
        return result

 

# 생성자의 매개변수를 전달해야 객체를 생성할 수 있음
test_const = FourCal()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[53], line 2
      1 # 생성자의 매개변수를 전달해야 객체를 생성할 수 있음
----> 2 test_const = FourCal()

TypeError: FourCal.__init__() missing 2 required positional arguments: 'first' and 'second'

 

test_const = FourCal(4, 2)
print(test_const.first)
print(test_const.second)
print(test_const.add())
4
2
6
728x90

'01_Python' 카테고리의 다른 글

46_Visual Studio Code설치(VS Code)  (0) 2025.01.13
45_클래스_심화  (0) 2025.01.10
43_파이썬 내장함수  (3) 2025.01.09
42_데이터 입출력  (1) 2025.01.09
41_함수  (0) 2025.01.08