[Python] 객체(Object)와 클래스(Class)

Sue·2022년 1월 5일

목차

객체와 클래스

  1. 객체(Object)
    • 객체 지향 프로그래밍(Object Oriented Programming)
  2. 클래스(Class)
    • Book 클래스 정의
    • Book 클래스 메소드 정의
  3. 인스턴스 속성(Instance Attribute)
    • Book 인스턴스 속성
  4. 클래스 속성(Class Attribute)
    • Book 클래스 속성
  5. 인스턴스 속성와 클래스 속성의 활용
    • Book 인스턴스 속성과 클래스 속성
  6. 클래스 매직 메소드(Class Masic Methods)
    • __init__()
    • __str__()
  7. 클래스 상속(Class Inheritance)
    • 메소드 오버라이딩(Method Overriding)
    • 클래스 상속, 메소드 오버라이딩 예제
  8. Reference

1. 객체(Object)

  • 객체란 존재하는 모든 것들을 의미
  • 현실 세계는 객체로 이루어져 있고, 모든 사건들은 사물 간의 상호작용을 통해 발생
  • 객체란 객체의 속성을 이루는 데이터들 뿐만 아니라 그 데이터의 조작방법에 대한 내용도 포함
  • 객체는 속성과 기능을 가지고 있는 것이 핵심

객체 지향 프로그래밍(Object Oriented Programming)

  • 객체 개념을 다루는 것이 객체 지향
  • 객체 지향 프로그래밍은 컴퓨터 프로그래밍 기법 중 하나
  • 프로그램을 단순히 데이터와 처리 방법으로 나누는 것이 아니라, 프로그램을 수많은 '객체'라는 단위로 구분하고, 이 객체들이 상호작용하는 방식
  • 각각의 객체는 메시지를 주고 받고, 데이터를 처리


2. 클래스(Class)

  • 객체의 구성 요소를 담는 개념
  • 여러 개의 속성(Attribute)과 메소드(Method)를 포함하는 개념
  • 객체를 정의하는 틀 또는 설계도
  • 실제 생성된 객체는 인스턴스(Instance)
  • 인스턴스는 메모리에 할당된 객체를 의미
  • 클래스 문법

class Name(object):

  • class: 클래스 정의
  • Name: 클래스 명
  • Object: 상속받는 객체명

Book 클래스 정의

  • 클래스 이름: Book
  • 속성
    - 저자: author
    • 책 이름: name
    • 출판사: publisher
    • 발행일: date
class Book(object):
  author = ""
  title = ""
  publisher = ""
  date = ""
book = Book()
book.author = 'Suan"
print(book.author)
book.title = 'Python Programming'
print(book.title)

Out:
Suan
Python Programming


Book 클래스 메소드 정의

메소드

  • 책 정보 출력: print_info(self)
  • self가 있어야만 실제로 인스턴스가 사용할 수 있는 메소드를 선언
  • print_info(self)에서 self는 실제적으로 book 인스턴스를 의미
  • 메소드 안에서 속성 값을 사용하지 않을 경우에는 self 생략 가능
class Book(object):
  author = ""
  title = ""
  publisher = ""
  date = ""

  def print_info(self):
    print("Author:", self.author)
    print("Title:", self.title)
book = Book()
book.author = 'Suan"
book.title = 'Python Programming'
book.print_info()

Out:
Author: Suan
Title: Python Programming


3. 인스턴스 속성(Instance Attribute)

  • 인스턴스 속성은 객체로부터 인스턴스가 생성된 후에 인스턴스에서 활용하는 속성

Book 인스턴스 속성

  • Book 클래스에서 생성된 인스턴스 b1에서 속성을 활용
class Book(object):
  author = ""
  title = ""
  publisher = ""
  date = ""

  def print_info(self):
    print("Author:", self.author)
    print("Title:", self.title)
    print("Publisher:", self.publisher)
    print("Date:", self.date)
b1 = Book()
b1.author = 'Suan'
b1.title = 'Python Programming'
b1.publisher = 'Colab'
b1.date = '2022'
b1.print_info()

Out:
Author: Suan
Title: Python Programming
Publisher: Colab
Date: 2022


4. 클래스 속성(Class Attribute)

  • 클래스 속성은 클래스 자체에서 사용되는 속성

Book 클래스 속성

class Book(object):
  author = ""
  title = ""
  publisher = ""
  date = ""

  def print_info(self):
    print("Author:", self.author)
    print("Title:", self.title)
    print("Publisher:", self.publisher)
    print("Date:", self.date)
b1 = Book()
Book.author = 'Suan'
Book.title = 'Python Programming'
Book.publisher = 'Colab'
Book.date = '2022'
b1.print_info()

Out:
Author: Suan
Title: Python Programming
Publisher: Colab
Date: 2022

b1 대신 클래스명으로 접근하였는데도 똑같이 출력된다.


5. 인스턴스 속성와 클래스 속성의 활용

  • 인스턴스 속성과 클래스 속성을 목적에 맞게 나누어서 활용

Book 인스턴스 속성과 클래스 속성

  • 인스턴스 속성
    • 저자: author
    • 제목: title
    • 출판사: publisher
    • 발행일: date
  • 클래스 속성
    • 수량: count
class Book(object):
  author = ""
  title = ""
  publisher = ""
  date = ""
  count = 0

  def print_info(self):
    print("Author:", self.author)
    print("Title:", self.title)
    print("Publisher:", self.publisher)
    print("Date:", self.date)
b1 = Book()
Book.count += 1
b1.author = 'Suan'
b1.title = 'Python Programming'
b1.publisher = 'Colab'
b1.date = '2022'
b1.print_info()
print("Number of Books", str(Book.count)

Out:
Author: Suan
Title: Python Programming
Publisher: Colab
Date: 2022
Number of Books: 1


6. 클래스 매직 메소드(Class Masic Methods)

  • '-'를 2개 붙여서 매직 메소드 또는 속성에 사용 가능
  • __을 속성 앞에 붙이면 가시성을 위한 속성으로 사용 가능
  • 클래스 매직 메소드의 종류
매직 메소드설명
__init__객체 초기화를 위해 클래스 생성시 호출되는 동작을 정의
__str__클래스의 인스턴스에서 str()이 호출될 때의 동작을 정의
__repr__클래스의 인스턴스에서 repr()이 호출될 때의 동작을 정의
__new__객체의 인스턴스화에서 호출되는 첫 번째 메소드
__del__객체가 소멸될 때 호출되는 메소드
__getattr__존재하지 않는 속성에 엑세스하려고 시도할 때 행위를 정의
__setattr__캡슐화를 위한 방법 정의
__add__두 인스턴스의 더하기가 일어날 때 실행되는 동작 정의
__lt__, __le__, __gt__, __ge__, __eq__, __ne__인스턴스 간의 <, <=, >,, >=, ==, != 비교 메소드

init()

  • init() 메소드를 이용하여 클래스의 속성들을 초기화
class Book(object):
  count = 0

  def __init__(self, author, title, publisher, data):
    self.author = author
    self.title = title
    self.publisher = publisher
    self.date = date
    
  def print_info(self):
    print("Author:", self.author)
    print("Title:", self.title)
    print("Publisher:", self.publisher)
    print("Date:", self.date)
book = Book('Suan', 'Python Programming', 'Colab', '2020')
book.print_info()
print("Number of Books", str(Book.count)

Out:
Author: Suan
Title: Python Programming
Publisher: Colab
Date: 2022
Number of Books: 2

  • count의 경우 한 번 실행할 때마다 1씩 증가된다.

str()

  • str() 메소드를 이용하여 인스턴스 출력
class Book(object):
  count = 0

  def __init__(self, author, title, publisher, data):
    self.author = author
    self.title = title
    self.publisher = publisher
    self.date = date

  def __str__(self):
    return ("Author:", self.author + \
            "\nTitle:", self.title + \
            "\nPublisher:", self.title + \
            "\nDate:", self.date)
book = Book('Suan', 'Python Programming', 'Colab', '2022')
print(book)
print('Number of Boos:', str(Book.count))

Out:
Author: Suan
Title: Python Programming
Publisher: Colab
Date: 2022
Number of Books: 2


7. 클래스 상속(Class Inheritance)

  • 기존 클래스에 있는 속성과 메소드를 그대로 상속받아 새로은 클래스를 생성
  • 공통된 클래스를 부모로 두고 자식들이 상속을 받아 클래스를 생성하므로 일관성 있는 프로그래밍 가능
  • 기존 클래스에서 일부를 추가/변경한 새로운 클래스 생성으로 코드 재사용(reuse) 가능
  • 클래스 상속 문법: class SubClass(SuperClass):
class SuperClass(object):
  pass

class SubClass(SuperClass):
  pass

class를 상속하는 방법은 class(상속할 클래스)이다. 생각보다 간단하다!


메소드 오버라이딩(Method Overriding)

  • SuperClass로부터 SubClass1SubClass2가 클래스 상속
  • 아무 내용도 없는 추상 메소드(Abstract Method) method()를 정의
  • Subclass1method()SuperClass의 추상 메소드를 오버라이딩
class SuperClass(object):
  def method(self):
    pass

class SubClass1(SuperClass):
  def method(self):
    print("Method Overriding")

class Subclass2(SuperClass):
  pass
sub1 = SubClass1()
sub2 = SubClass2()

sub1.method()
sub2.method()

Out:
Method Overriding

출력값으로 'Method Overriding'이 나왔습니다.

이 결과는 sub1이 호출한 결괏값입낟.

그런데 SubClass2를 받은 sub2의 경우 호출할 게 아무 것도 없는데 error가 나지 않습니다.

그 이유는 SuperClass를 상속 받아서 이미 method 정의를 그대로 가져왔기 때문에 호출될 수 있었습니다.


클래스 상속, 메소드 오버라이딩 예제

  • Vehicle 클래스를 상속받아 Car 클래스와 Truck 클래스 생성
  • Car 클래스와 Truck 클래스는 up_speed 메소드를 오버라이딩
  • Car 클래스는 속도가 240 초과되면 240으로 조정
  • Truck 클래스는 속도가 180 초과되면 180으로 조정
class Vehicle(object):
  speed = 0
  def up_speed(self, value):
    self.speed += value

  def down_speed(self, value):
    self.speed -= value

  def print_speed(self):
    print("Speed:", str(self.speed))

class Car(Vehicle):
  def up_speed(self, value):
    self.speed += value
    if self.speed > 240: self.speed = 240

class Truck(Vehicle):
  def up_speed(self, value):
    self.speed += value
    if self.speed > 180: self.speed = 180
car = Car()
car.up_speed(300)
car.print_speed()

truck = Truck()
truck.up_speed(200)
truck.print_speed()

Out:
Speed: 240
Speed: 180


Reference

🎥 유튜브 파이썬 쉽게 배우기 - 08 객체와 클래스
📸 이미지는 ppt 수작업하였습니다. ✨

profile
AI/ML Engineer

0개의 댓글