TIL

[TIL] 9일차_PYTHON_Class

Molybdenum_j 2023. 3. 3. 18:00

▶ class

  • 변수, 함수를 묶어서 코드를 작성하는 방법
  • 객체지향 구현하는 문법
    • 객체지향 : 실제세계를 모델링하여 프로그램을 개발하는 개발 방법론 = 협업을 용이하게 하기 위해
  • 함수 사용법 : 함수선언(코드작성) -> 함수호출(코드실행)
  • 클래스 사용법
    • 클래스선언(코드작성) -> 객체생성(메모리 사용) -> 메서드실행(코드실행)
    • 클래스선언(설계도작성) -> 객체생성(제품생산) -> 메서드 실행(기능사용)
  • 식별자컨벤션
    • 변수, 함수 : snake_case
    • 클래스 : PascalCase, UpperCamelCase
  • class, self, 사용자 정의 데이터 타입, special methods(__init__(), __add__() ...)
  • 상속, super, getter-setter, mangling, 메서드의 종류들(인스턴스, 클래스, 스태틱)
 
  • 클래스 선언 : 코드작성
    • 계산기 설계 : Calculator : number1, number2, plus(), minus()
class Calculator :

    number1, number2 = 1, 2

    def plus(self):
        return self.number1 + self.number2

    def pminus(self):
        return self.number1 - self.number2

 

  • 객체생성 : 메모리 사용
calc1 = Calculator()
calc2 = Calculator()
  • dir() : 객체에 들어있는 변수와 메소드를 출력
[var for var in dir(calc1) if var[0] != '_']

['number1', 'number2', 'plus', 'pminus']

 

  • 메서드 실행 : 코드실행
calc1.plus(), calc1.minus()

(3, -1)

 

  • 객체의 변수 수정 : 데이터 선택 = 수정 할 데이터
calc1.number1, calc1.number2, calc2.number1, calc2.number2

(1, 2, 1, 2)
calc1.number1 = 20
calc1.number1, calc1.number2, calc2.number1, calc2.number2

(20, 2, 1, 2)

 


 

▶ self : 객체 자신

calculator.plus() : self.number1 + self.number2

calc.plus() : self == calc1

  • self.number1 + self.number2 -> calc.number1 + calc1.number2

▶ 스페셜 메서드

특별한 기능을 하는 메서드 : 앞뒤로 __를 붙임

▶ 생성자 메서드 : __init__()

  • 객체를 생성할 때 실행되는 메서드로 변수의 초기값을 설정할 때 주로 사용한다.
  • 불량 객체(메서드 사용 x)가 만들어질 확률을 줄여준다.


 

<클래스 사용법>

  1. 클래스 생성 : 설계도 작성
class Account:

    def __init__(self, balance=20000):
        self.balance = balance

    def insert(self, amount):
        self.balance += amount
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
        else:
            print(f'잔액이 {amount - self.balance}원 부족합니다.')

 

2. 객체생성 : 메모리사용 = 자원사용

account = Account()

 

3. 메서드 실행 : 코드 실행 = 기능사용 -> 불량품 생산을 줄임

account.insert(3000)

account.balance

23000

 


 

클래스는 사용자 정의 데이터 타입이다.

  • account 객체가 만들어진 클래스는 Account
    • 데이터 타입 == 클래스 -> 클래스는 데이터 타입이다.
    • Account 클래스는 우리가 만든다. = 사용자 정의
      • 클래스는 사용자 정의 데이터 타입이다.
type(account)

__main__.Account

 

  • data의 데이터 타입은 list
    • data 객체가 만들어진 클래스는 list
    • list 클래스는 우리가 만들지 않는다.
data = [1,2,3]
type(data)

list

 

-> account의 메서드는 Account 클래스에서 정의한다.

-> data의 메서드는 list 클래스에서 정의한다.

 

데이터 타입의 메서드를 암기할 필요가 없다.

 

print([var for var in dir(data) if var[0] != '_'])

['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

  • account : 클래스, 데이터 타입 : Account : 사용자 정의 데이터 타입 o
    • data1 : 클래스, 데이터 타입 : str : 사용자 정의 데이터 타입x
    • data2 : 클래스, 데이터 타입 : listr : 사용자 정의 데이터 타입x
type(account), type(data1), type(data2)

(__main__.Account, str, list)

 

▶ 추가적인 스페셜 메서드

__add__() : + 연산자 정의

__str__() : print() 함수 실행 정의

  • 데이터 타입에 따라서 수행되는 연산이 다르다.
d1, d2, d3, d4 = 1, 2, '3', '4'
d1 +d2, d3 + d4

(3, '34')

 

  • d1 + d2 : + 연산자 == d1.__add__() 실행
d1 + d2, d1.__add__(d2), d3 + d4, d3.__add__(d4)

(3, 3, '34', '34')

 

  • d1 + d2 : d1.__add__(d2) : d1.__add__() : int 클래스의 __add__() 메서드
  • d3 + d4 : d3.__add__(d4) : d3.__add__() : str클래스의 __add__() 메서드

-> 데이터 타입에 따라서 수행되는 __add__() 메서드가 다르다.

d5, d6 = [1, 2], [3, 4]
d5 + d6

[1, 2, 3, 4]
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
arr1 + arr2

array([4, 6])

 

  • 덧셈 연산을 하지만 뺄셈연산이 수행되는 객체를 생성
class Number:

    def __init__(self, data):
        self.data = data
    
    def __add__(self, obj):
        return self.data - obj.data
num1 = Number(10)
num2 = Number(3)
num1.data, num2.data

(10, 3)
num1 + num2

7

 


 

▶ 상속

다른 클래스의 변수(메서드)를 가져와서 사용하는 방법

-> 특정 메서드만 변경은 가능하나 제외는 불가

  • 다중상속
class Human:
    def walk(self):
        print('walking!')

class Korean:
    def eat(self):
        print('eat kimchi!')

class Indian:
    def eat(self):
        print('eat curry!')
# Human > Korea > Jin
class Jin(Korean, Human):
    def skill(self):
        print('coding')
jin = Jin()
show_vars(jin)

['eat', 'skill', 'walk']

 

 

출처-멋쟁이사자처럼_ AISCHOOL_박두진강사님