오늘도 개발
파이썬 객체(Object) 본문
1. 클래스(Class)와 객체(Object)
클래스
클래스는 템플릿 코드이고 객체는 템플릿을 이용해 만든 결과물이다.
클래스는 쿠키틀이고 객체는 틀로 찍어낸 쿠키라고 할 수 있다.
클래스 속성(class attribute)과 클래스 메서드(class method)를 가질 수 있다.
객체(인스턴스)
객체는 인스턴스라고도 부른다.
인스턴스는 주로 클래스와 객체의 관계를 설명할 때 사용하는 말이다.
아래 코드에서 sue 객체는 Person 클래스의 인스턴스(instance)이다.
객체는 인스턴스 속성(attribute)과 인스턴스 메서드(method)를 가질 수 있다.
속성은 객체가 갖는 변수이고, 메서드는 객체가 갖는 함수이다.
속성은 상태이고 메서드는 동작이라고 생각해도 된다.
메서드의 첫 번째 파라미터로는 대체로 self를 사용한다.
self는 클래스의 현재 인스턴스를 나타낸다.
# 클래스
class Person:
def __init__(self, name):
# 속성
self.name = name
# 메서드
def greet(self):
print('Hello, ' + self.name)
# 객체
sue = Person('Sue')
sue.greet()
# 'Hello, Sue'
클래스와 인스턴스는 각자 다른 메모리에 저장된다.

2. 생성자(Constructor)
클래스는 생성자를 가질 수 있다.
생성자는 객체가 생성될 때 자동으로 호출되는 메서드이다.
보통 객체에 초깃값을 설정할 때 사용한다.
대표적으로 __init__이 있다.
class Person:
def __init__(self, name):
# 인스턴스에 name 변수 생성
# 인스턴스의 name 변수에 인스턴스 생성 시 받은 입력값을 저장
self.name = name
sue = Person('Sue')
3. 상속(Inheritance)
클래스를 만들 때 다른 클래스의 기능을 물려받는 것을 상속이라고 한다.
기존 클래스를 수정할 수 없는 상황일 때 주로 사용한다.
상속하는 클래스를 기반 클래스(parent class, super class, base class)라고 하고
상속받는 클래스를 파생 클래스(child class, subclass, derived class)라고 한다.
기반 클래스와 파생 클래스는 is-a 관계를 갖는다.
(예 : Student is a Person, 파생 클래스 is a 기반 클래스)
상속하기
# 기반 클래스
class Person:
def greeting(self):
print('hi')
# 파생 클래스
class Student(Person):
def study(self):
print('Studying!')
sue = Student()
sue.greeting() # hi
sue.studying() # Studying!
기반 클래스 init 물려받기 : super()
자식 클래스가 인스턴스를 만들 때는 자동으로 부모 클래스의 init을 호출한다.
하지만 자식 클래스에서 init 메서드를 재정의한 경우에는 부모 클래스의 init을 자동으로 호출하지 않는다.
자식 클래스에서 init 메서드를 재정의하면서 부모 클래스의 init도 호출하려면 super().__init__()을 사용해야 한다.
super()는 부모 클래스를 반환하는 함수이다.
즉 super().__init__()은 부모 클래스의 init 메서드를 호출하는 코드이다.
다음은 부모 클래스의 init이 호출되지 않은 경우이다.
# 부모 클래스
class Person:
def __init__(self):
print('Person init')
self.country = 'Korea'
# 자식 클래스
class Student(Person):
def __init__(self):
print('Student init')
self.subject = 'coding'
sue = Student()
print(sue.country)
# Student init
# AttributeError: 'Student' object has no attribute 'country'
super()를 사용하면 이렇게 해결할 수 있다.
# 부모 클래스
class Person:
def __init__(self):
print('Person init')
self.country = 'Korea'
# 자식 클래스
class Student(Person):
def __init__(self):
# 부모 클래스의 init 호출
super().__init__()
print('Student init')
self.subject = 'coding'
sue = Student()
print(sue.country)
# Person init
# Student init
# Korea
메서드 오버라이딩(Method Overriding)
자식 클래스는 상속받은 메서드를 수정할 수 있는데
이것을 메서드 오버라이딩이라고 한다.
상속받은 메서드를 완전히 새로 정의할 수도 있고,
# 부모 클래스
class Person:
def greet(self):
print('hello')
# 자식 클래스
class Student(Person):
def greet(self):
print('hi')
sue = Student()
print(sue.greet())
# hi
super()를 사용하여 원래 메서드의 기능을 유지하면서 새로운 기능을 덧붙일 수도 있다.
# 부모 클래스
class Person:
def greet(self):
print('hello')
# 자식 클래스
class Student(Person):
def greet(self):
super().greet()
print('hi')
sue = Student()
sue.greet()
# hello
# hi
4. 클래스 속성과 메서드
클래스 속성은 클래스에 작성하는 속성으로 모든 인스턴스가 공유한다.
인스턴스 속성만큼 자주 사용하지는 않는다.
class Person:
bag = []
def put_bag(self, stuff):
Person.bag.append(stuff)
sue = Person()
alice = Person()
sue.put_bag('chocolate')
alice.put_bag('candy')
print(Person.bag)
# ['chocolate', 'candy']
5. 추상 클래스(Abstract class)
메서드 목록을 가진 클래스를 추상 클래스라고 한다.
자식 클래스에서 메서드 구현을 강제하기 위해 사용한다.
추상 클래스에는 보통 메서드의 이름만 넣고 구현하지는 않는다.
아래 코드에서 StudentBase를 상속받은 자식 클래스가
study 메서드를 정의하지 않으면 오류가 난다.
from abc import *
class StudentBase(metaclass=ABCMeta):
# 자식 클래스가 만들어야 할 메서드 정의
# 자식 클래스에서 만들지 않으면 오류 발생
@abstractclassmethod
def study(self):
pass
class Student(StudentBase):
def study(self):
print('study')
참고
'웹 프로그래밍 > Python3' 카테고리의 다른 글
| 파이썬 모듈과 패키지(Module & Package) (0) | 2022.06.23 |
|---|---|
| 파이썬 인수(Argument)의 종류와 규칙 (0) | 2022.06.23 |
| 파이썬 함수(function) (0) | 2022.06.07 |
| CPython이 함수를 처리하는 방법 (0) | 2022.06.07 |
| for문과 range()함수 (0) | 2022.06.05 |