자료구조(파이썬) - (배경지식)클래스 Class

LSH·2023년 7월 31일
0

교육 정보

  • 교육 명: 경기미래기술학교 AI 교육
  • 교육 기간: 2023.05.08 ~ 2023.10.31
  • 오늘의 커리큘럼:
    파이썬 자료구조
    (7/17 ~ 7/28)
  • 강사: 이현주, 이애리 강사님
  • 강의 계획:
    1. 자료구조

Class

객체 지향 프로그래밍

  • 실제 세계가 사물로 구성되어있든 소프트웨어도 객체로 구성하는 방법
  • 반대 개념: 원시타입 ex) c언어, 넘파이(c언어로 만들어진 모듈, 빠른 속도가 특징)
  • 원시타입 언어에서 변수에 값을 부여할 경우 해당 변수에 값이 독립적으로 저장되지만 객체지향 언어의 경우 변수에 해당 메모리의 주소가 저장(참조)

클래스

: 특정 객체를 만들기 위해 만들어진 수단


  • 클래스 생성, 생성자, 소멸자
class Car:

# 객체 속성
  brand = ''
  model = ''
  color = ''

  def __init__(self, brand, model, color):
      self.brand = brand
      self.model = model
      self.color = color
      print(brand, model, color, ' 객체가 생성되었습니다.')



# 객체메소드 정의
  def turn_on(self):
    print(self.model, 'turn on')

  def turn_off(self):
    print(self.model, 'turn off')

  def drive(self):
    print(self.model, 'is driving')



  def show_info(self):
    print(f'{self.brand}{self.color} {self.model}입니다.')


  def __del__(self):
    print(f'{self.model}자동차 객체가 삭제되었습니다.')

# 다양한 자동차 객체를 생성합니다.

my_car  = Car('현대','소나타', '흰색')
car1  = Car('기아', '소렌토', '검정색')

# 생성한 객체의 메소드를 호출합니다.
my_car.show_info()
car1.show_info()
del car1
del my_car

#
# 결과

현대 소나타 흰색  객체가 생성되었습니다.
기아 소렌토 검정색  객체가 생성되었습니다.
현대의 흰색 소나타입니다.
기아의 검정색 소렌토입니다.
소렌토자동차 객체가 삭제되었습니다.
소나타자동차 객체가 삭제되었습니다.
소나타자동차 객체가 삭제되었습니다.

  • 클래스 상속
class Parent:
  def __init__(self, name):
    self.name = name

class Child(Parent):
  pass

c = Child('이름')
print(c.name)
#
# 결과
이름
  • 상속한 부모의 클래스 사용 super()
class Parent:
  def __init__(self, name):
    self.name = name

class Child(Parent):
  def __init__(self, name, age):
    super().__init__(name)
    self.age = age

c =Child("도라이몽",12)
print(c.name,c.age)
#
# 결과
도라이몽 12
  • 상속한 부모 클래스의 메소드 호출
class Parent:
  def __init__(self, name):
    self.name = name

  def print_name(self):
    print("Parent")

class Child(Parent):
  def __init__(self, name, age):
    super().__init__(name)
    self.age = age

c =Child("도라이몽",12)
c.print_name()
#
# 결과
Parent

  • 클래스 오버라이딩 overriding
class Animal:
    def say(self, message):
      print(message)

class Dog(Animal):
    pass

class Bird(Animal):
    def say(self, message):
      print(f'birds says, {message}')

dog1 = Dog()
dog1.say('bark')
# 상속받은 메소드를 사용

bird1 = Bird()
bird1.say('tweet')
# 상속받은 메소드를 무시하고 새로 정의한 메소드를 사용 → 다형성
#
# 결과
bark
birds says, tweet

  • 클래스 오버로딩 overloading
    • 파이썬은 완전한 오버로딩을 지원하지는 않음
class Method:
    def  __init__(self, obj):
        self.obj = obj

# 들어온 매개변수가 int인지 아닌지 확인하여 value를 반환 (다시 확인)
    def  _value_check(self, value):
        return value if isinstance(value, int) else int (value)


# 기본적인 형태의 연산 함수 (__add__, 등 을 수정하여 리스트 연산의 형태로 바꿔줌 )
    def __add__(self, value):
        value = self._value_check(value)
        self.obj = [x + value for x in self.obj]
        return self

    def __sub__(self, value):
        value = self._value_check(value)
        self.obj = [x - value for x in self.obj]
        return self

    def __mul__(self, value):
        value = self._value_check(value)
        self.obj = [x * value for x in self.obj]
        return self

    def __truediv__(self, value):
        value = self._value_check(value)
        self.obj = [x / value for x in self.obj]
        return self

m = Method([1,2,3,4,5])
m = m+3
print(m.obj)
m = m-3
print(m.obj)
m = m*3
print(m.obj)
m = m/3
print(m.obj)
#
# 결과
[4, 5, 6, 7, 8]
[1, 2, 3, 4, 5]
[3, 6, 9, 12, 15]
[1.0, 2.0, 3.0, 4.0, 5.0]

  • 클래스 변수와 클래스 함수
import random

#계좌 잔고 예금주

class Account:
    # 클래스 변수
    count = 0 # 객체의 수를 저장하는 변수
    accounts = [] # 객체를 저장하는 변수
    deposit_count = 0
    account_log = list()

    @classmethod
    def get_account_num(cls):
      print(cls.count)

    def __init__(self, name, balance):
      self.name = name
      self.account_num = f'{random.randint(0, 999):03d}-{random.randint(0, 99):02d}-{random.randint(0, 999999):06d}'
      # :0.3d 로 자릿수 지정 안해주면 앞자리가 0일때 자릿수가 줄어들 수 있음
      self.balance = balance
      self.bank = 'bank'
      # self.deposit_count 여기에 선언해도 됨 -> self로
      self.count += 1

    def deposit(self, num):
      if num > 0:
        self.balance += num
        self.deposit_count += 1
        if (self.deposit_count % 5) == 0 :
          self.balance = self.balance * 1.01
        print(f'{num}입금, 잔액: {self.balance}')
        self.account_log.append(f'{num}입금, 잔액: {self.balance}')
      else:
        print('입금액은 0원 이상이어야 합니다.')

    def withdraw(self, num):
      if self.balance >= num:
        self.balance -= num
        print(f'{num}출금, 잔액: {self.balance}')
        self.account_log.append(f'{num}출금, 잔액: {self.balance}')
      else:
        print('잔액 부족')


    def display_info(self):
      print(self.bank)
      print(f'{self.name = }')
      print(f'{self.account_num = }')
      print(f'{self.balance = }')


    def account_history(self):
      print('=============Account history=============')
      for log in self.account_log:
        print(log)

p1 = Account('p',10000)
p1.deposit(10000)
p1.deposit(10000)
p1.deposit(10000)
p1.deposit(10000)
p1.deposit(10000)
p1.display_info()

p1.account_history()


#
# 결과

10000입금, 잔액: 20000
10000입금, 잔액: 30000
10000입금, 잔액: 40000
10000입금, 잔액: 50000
10000입금, 잔액: 60600.0
bank
self.name = 'p'
self.account_num = '890-99-202686'
self.balance = 60600.0
=============Account history=============
10000입금, 잔액: 20000
10000입금, 잔액: 30000
10000입금, 잔액: 40000
10000입금, 잔액: 50000
10000입금, 잔액: 60600.0
profile
:D

0개의 댓글