Skip to main content

Command Palette

Search for a command to run...

Introduction to Classes and Objects in Python Programming

Understanding of class in Python

Updated
11 min read
Introduction to Classes and Objects in Python Programming

1️⃣ 클래스와 객체의 정의(Definition of Classes and Objects)
2️⃣ 클래스와 객체의 특징(Characteristics of Classes and Objects)
3️⃣ 클래스의 구성요소(Components of a Class)
4️⃣ 클래스 변수와 인스턴스 변수의 개념
(Concepts of Class Variables and Instance Variables)
5️⃣ 사칙 연산 클래스 구상하기 (Designing a Basic Arithmetic Operation Class)
6️⃣ 사칙 연산 클래스 만들기 (Creating an Arithmetic Operation Class)
7️⃣ 생성자 (Constructor)


객체 지향 프로그래밍(Object-oriented programming) Object-oriented programming is a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields, and code in the form of procedures. In OOP, computer programs are designed by making them out of objects that interact with one another.

파이썬은 객체 지향 프로그래밍으로 위에서 언급된 class와 objects를 오늘 학습할 예정이다.

1️⃣ 클래스와 객체의 정의

(Definition of Classes and Objects)

  • 클래스는 여러 함수와 변수들을 사용하여 템플릿 형태로 사용가능 하게 정의해 놓은 것이다.

  • 객체란 템플릿 형태의 클래스를 활용하여 특정한 일을 하도록 인스턴스화 한 것이다.

  • 객체 마다 고유한 특징이 있으며 동일 클래스로 만든 객체라도 서로 전혀 영향을 주지 않는다.

클래스와 객체란 무엇일까? (What is classes and objects?)

클래스(classes)

  • 여러 함수와 변수들을 사용하여 템플릿 형태로 사용가능 하게 정의해 놓은 것

객체(objects)

  • 템플릿 형태의 클래스를 활용하여 특정한 일을 인스턴스화, 구체화 한 것이다.

2️⃣ 클래스와 객체의 특징

(Characteristics of Classes and Objects)

  • 각 클래스로 생성된 객체는 고유한 특징을 가진다.

  • 동일한 클래스에서 생성된 객체들은 서로 영향을 주지 않는다

#파이썬 클래스 만들기 예제
class Cookie: #클래스 이름은 대문자를 써서 함수와 구분한다.
     pass #새로 만든 클래스를 구현하는 곳이다

#이렇게 정의된 클래스는 프로세스의 형태로 RAM메모리에 임시저장된다.
# Cookie 클래스의 객체를 만드는 방법
a = Cookie()
b = Cookie()
  • Robot() 클래스로부터 Robot1, Robot2의 객체(objects)를 만들었다.

  • 객체를 생성할때도 함수 호출할때와 신택스가 비슷하다. 이러한 이유로 클래스의 첫글자를 대문자로 지어서 함수와 구분한다.

3️⃣ 클래스의 구성요소

(Components of a Class)

  1. 매서드(Methods): 클래스 안에서 정의된 함수

  2. 클래스 변수(Class variables): 클래스 안에서 정의된 변수

  3. 인스턴스 변수(Instance variables): 객체의 생성으로 정의된 변수

class Stock:
    market = "kospi"  # 클래스 변수

    def transaction(self, name):  # 매서드
        self.name = name  # 인스턴스 변수
        print("주식을 매수했습니다")
  • marketStock 클래스의 클래스 변수로서 "kospi"로 초기화된다.

  • transactionStock 클래스의 메서드로, 인스턴스를 사용하여 호출될 때 작동한다.

  • self.nametransaction 메서드에서 인스턴스 변수로 사용되며, 각 인스턴스마다 다른 값이 할당될 수 있다.

class Robot:
    robot_model = "t800"  # 클래스 변수

    def set_position(self, x, y):   # 메서드(method)
        self.x = x       # 인스턴스 변수
        self.y = y       # 인스턴수 변수

    def forward(self, a, b):   # 앞으로 이동
        self.x += a    #  a 만큼 앞으로
        self.y += b    # b 만큼 앞으로


    def backward(self, a, b):   # 앞으로 이동
        self.x -= a    #  a 만큼 뒤로
        self.y -= b    # b 만큼 뒤로

4️⃣ 클래스 변수와 인스턴스 변수의 차이점(Difference between Class Variables and Instance Variables)

Class Variables

A class variable is something that belongs to the recipe itself. Let's say our recipe is for "Chocolate Chip Cookies."

  • Class Name: ChocolateChipCookies

  • Class Variables: These are the things that are common to all cookies made from this recipe. For example, the type of flour, sugar, or the default number of chocolate chips per cookie.

When you write the recipe, you might say:

class ChocolateChipCookies:
    flour = "2 cups"
    sugar = "1 cup"
    chocolate_chips = "1/2 cup"

Here, flour, sugar, and chocolate_chips are class variables. No matter how many batches of cookies you make, they all start with these same basic ingredients.

Instance Variables

Instance variables are like the special characteristics of each individual batch of cookies you bake. Each batch can be a little different.

  • Instance Variables: These are the details that can change from one batch to another, like the number of cookies in a batch, the baking time, or the oven temperature.

When you bake a batch of cookies, you might have:

class ChocolateChipCookies:
    flour = "2 cups"
    sugar = "1 cup"
    chocolate_chips = "1/2 cup"

    def __init__(self, number_of_cookies, baking_time, oven_temperature):
        self.number_of_cookies = number_of_cookies
        self.baking_time = baking_time
        self.oven_temperature = oven_temperature

Here, number_of_cookies, baking_time, and oven_temperature are instance variables. Each time you bake a batch, you can set these to different values:

batch1 = ChocolateChipCookies(12, "15 minutes", "350 degrees")
batch2 = ChocolateChipCookies(24, "12 minutes", "375 degrees")

print(f"Batch 1: {batch1.number_of_cookies} cookies, bake for {batch1.baking_time} at {batch1.oven_temperture}")
print(f"Batch 2: {batch2.number_of_cookies} cookies, bake for {batch2.baking_time} at {batch2.oven_temperture}")

In this example:

  • batch1 will have 12 cookies, bake for 15 minutes at 350 degrees.

  • batch2 will have 24 cookies, bake for 12 minutes at 375 degrees.

Summary

  • Class Variables: These are the same for all instances of a class. They're like the ingredients that don't change in the recipe.

  • Instance Variables: These can be different for each instance. They're like the specific details for each batch you bake.

💡The __init__ method in Python is a special method known as the initializer or constructor. Its main purpose is to initialize an object's attributes when it is created. Think of it like a setup function that gets called automatically every time you create a new instance of a class.

생성자(constructor)란 객체가 생성될 때 자동으로 호출되는 메서드를 의미한다. 파이썬 메서드명으로 __init__를 사용하면 이 메서드는 생성자가 된다.

Using our cookie example from before, let's break it down:

Purpose of __init__

When you bake a batch of cookies, you need to decide how many cookies you want, how long to bake them, and at what temperature. The __init__ method helps you set up these details for each batch.

Example

Here's our ChocolateChipCookies class with the __init__ method:

class ChocolateChipCookies:
    flour = "2 cups"
    sugar = "1 cup"
    chocolate_chips = "1/2 cup"

    def __init__(self, number_of_cookies, baking_time, oven_temperature):
        self.number_of_cookies = number_of_cookies
        self.baking_time = baking_time
        self.oven_temperature = oven_temperature

How __init__ Works

  1. Class Definition: You define the class ChocolateChipCookies with class variables (flour, sugar, chocolate_chips).

  2. Initializer (__init__): You define the __init__ method to take additional parameters (number_of_cookies, baking_time, oven_temperature). Inside __init__, you assign these parameters to instance variables using self.

  3. Creating Instances: When you create a new batch of cookies (an instance of the class), you call the class and pass in the parameters. The __init__ method gets called automatically to set up the instance with those values.

Example Usage

Creating two batches of cookies:

batch1 = ChocolateChipCookies(12, "15 minutes", "350 degrees")
batch2 = ChocolateChipCookies(24, "12 minutes", "375 degrees")

Here's what happens step-by-step when you create batch1:

  1. Create Instance: batch1 = ChocolateChipCookies(12, "15 minutes", "350 degrees")

  2. Call __init__: The __init__ method is called with self (the new object), number_of_cookies=12, baking_time="15 minutes", and oven_temperature="350 degrees".

  3. Initialize Instance Variables: Inside __init__, the instance variables are set:

     self.number_of_cookies = 12
     self.baking_time = "15 minutes"
     self.oven_temperature = "350 degrees"
    

Now, batch1 has its own specific values for number_of_cookies, baking_time, and oven_temperature.

Summary

  • The __init__ method initializes new objects with specific attributes.

  • It gets called automatically when you create a new instance of a class.

  • You can use it to set up instance variables for each object.

Think of __init__ as the setup step where you get everything ready for each new batch of cookies.

__init__ 메서드는 setdata 메서드와 이름만 다르고 모든 게 동일하다. 단, 메서드 이름을 __init__로 했기 때문에 생성자로 인식되어 객체가 생성되는 시점에 자동으로 호출된다는 차이가 있다.


5️⃣ 사칙 연산 클래스 구상하기

(Designing a Basic Arithmetic Operation Class)

파이썬에서 사칙연산을 가능하게 하는 FourCal 클래스를 만드는 과정을 단계별로 살펴보자

  1. 클래스 구조 만들기 (Creating the class structure)

  2. 객체에 연산할 숫자 지정하기 (Make objects assignable numbers)

  3. 더하기 기능 만들기 (Creating the addition functionality)

  4. 곱하기, 빼기, 나누기 기능 만들기 (Creating the Multiplication, Subtraction, and Division Functionalities)


  1. 클래스 구조 만들기 (Creating the class structure)

먼저, 기본 클래스 구조를 정의한다. 아직 구체적인 기능은 포함하지 않은 템플릿을 만든다. Fourcal 클래스는 아무 변수나 함수도 포함하지 않지만 객체를 만들 수 있는 기능이 있다. 아래와 같이 작성하면 아무 메서드나 속성도 포함하지 않은 빈 클래스 FourCal이 생성된다.

class FourCal:
    pass
  • pass is a syntax that does nothing, and is often used to write temporary code.
a = FourCal()
type(a)

<class '__main__.FourCal'>
  • 위와 같이 a = FourCal()로 a 객체를 먼저 만든 후 type(a)로 a 객체가 어떤 타입인지 알아보았다. 역시 객체 a가 FourCal 클래스의 인스턴스라는 것을 알 수 있다.

  1. 객체에 연산할 숫자 지정하기 (Make objects assignable numbers)

https://wikidocs.net/28 출처

생성된 객체 a는 아직 아무런 기능도 하지 못한다. 이제 더하기, 빼기, 곱하기, 나누기 등의 기능을 하는 객체를 만들어야 한다. 그런데 이러한 기능을 갖춘 객체를 만들려면 먼저 사칙 연산을 할 때 사용할 2개의 숫자를 a 객체에게 알려 주어야 한다. 다음과 같이 연산을 수행할 대상(4, 2)을 객체에 지정할 수 있게 만들어 보자.

a.setdata(4, 2)
>>> class FourCal:
...     def setdata(self, first, second): #매서드의 매개변수
...         self.first = first #매서드의 수행문
...         self.second = second #매서드의 수행

앞에서 만든 FourCal 클래스에서 pass 문장을 삭제하고 그 대신 setdata 함수를 정의했다. 클래스 안에 구현된 함수는 다른 말로 메서드(method)라고 부른다. 앞으로 클래스 내부의 함수는 항상 메서드라고 표현할 테니 메서드라는 용어를 기억해 두자.

setdata 메서드의 매개변수

setdata 메서드를 좀 더 자세히 살펴보자. setdata 메서드는 매개변수로 self, first, second 3개의 입력값을 받는다. 그런데 일반 함수와 달리, 메서드의 첫 번째 매개변수 self는 특별한 의미를 가진다.

다음과 같이 a 객체를 만들고 a 객체를 통해 setdata 메서드를 호출해 보자.

>>> a = FourCal()
>>> a.setdata(4, 2)
  • 객체를 이용해 클래스의 메서드를 호출하려면 a.setdata(4, 2)와 같이 도트(.) 연산자를 사용하면 된다.\

그런데 뭔가 좀 이상하지 않은가? setdata 메서드에는 self, first, second 총 3개의 매개변수가 필요한데 실제로는 a.setdata(4, 2)처럼 2개의 값만 전달했다. 왜 그럴까? a.setdata(4, 2)처럼 호출하면 setdata 메서드의 첫 번째 매개변수 self에는 setdata 메서드를 호출한 객체 a가 자동으로 전달되기 때문이다. 다음 그림을 보면 객체를 호출할 때 입력한 값이 메서드에 어떻게 전달되는지 쉽게 이해할 수 있을 것이다.

파이썬 메서드의 첫 번째 매개변수 이름은 관례적으로 self를 사용한다. 객체를 호출할 때 호출한 객체 자신이 전달되기 때문에 self라는 이름을 사용한 것이다. 물론 self말고 다른 이름을 사용해도 상관없다.

메서드의 첫 번째 매개변수 self를 명시적으로 구현하는 것은 파이썬만의 독특한 특징이다. 예를 들어 자바와 같은 언어는 첫 번째 매개변수 self가 필요없다.

setdata 메서드의 수행문

이제 setdata 메서드의 수행문에 대해 알아보자.

def setdata(self, first, second):   # 메서드의 매개변수
    self.first = first              # 메서드의 수행문
    self.second = second            # 메서드의 수행문

a.setdata(4, 2)처럼 호출하면 setdata 메서드의 매개변수 first, second에는 각각 값 4와 2가 전달되어 setdata 메서드의 수행문이 다음과 같이 해석된다.

self.first = 4
self.second = 2

#self는 전달된 객체 a이므로 다시 다음과 같이 해석된다.

a.first = 4
a.second = 2

a.first = 4라는 문장이 수행되면 a 객체에 객체변수 first가 생성되고 4라는 값이 저장된다. 이와 마찬가지로 a.second = 2라는 문장이 수행되면 a 객체에 객체변수 second가 생성되고 2라는 값이 저장된다.

객체에 생성되는 객체만의 변수를 ‘객체변수’ 또는 ‘속성’이라고 부른다.

>>> a = FourCal()
>>> a.setdata(4, 2)
>>> a.first
4
>>> a.second
2

a 객체에 객체변수 first와 second가 생성된 것을 확인할 수 있다. 이번에는 다음과 같이 a, b 객체를 만들어 보자.

>>> a = FourCal()
>>> b = FourCal()

그리고 a 객체의 객체변수 first를 다음과 같이 생성한다.

>>> a.setdata(4, 2)
>>> a.first
4

이번에는 b 객체의 객체변수 first를 다음과 같이 생성한다.

>>> b.setdata(3, 7)
>>> b.first
3

다음은 현재까지 완성된 FourCal 클래스이다.

>>> class FourCal:
...     def setdata(self, first, second):
...         self.first = first
...         self.second = second

지금까지 살펴본 내용이 바로 이 4줄의 소스 코드를 설명하기 위한 것이었다. 앞에서 설명한 것들이 이해되지 않는다면 다시 한번 읽어 보기 바란다. 이 부분을 이해하지 못하면 다음으로 넘어갈 수 없기 때문이다.


더하기 기능 만들기 (Creating the addition functionality)

2개의 숫자 값을 설정해 주었으므로 2개의 숫자를 더하는 기능을 방금 만든 클래스에 추가해 보자.

>>> class FourCal:
...     def setdata(self, first, second):
...         self.first = first
...         self.second = second

...     def add(self):
...         result = self.first + self.second
...         return result

add 메서드를 새롭게 추가했다. 이제 클래스를 사용해 보자.

>>> a = FourCal()
>>> a.setdata(4, 2)

위와 같이 호출하면 앞에서 살펴보았듯이 a 객체의 first, second 객체변수에는 각각 값 4와 2가 저장될 것이다.

이제 add 메서드를 호출해 보자.

a.add()

a.add()라고 호출하면 add 메서드가 호출되어 값 6이 출력될 것이다. 어떤 과정을 거쳐 값 6이 출력되는지 add 메서드를 따로 떼어 내 자세히 살펴보자.

def add(self):
    result = self.first + self.second
    return result
  • add 메서드의 매개변수는 self, 리턴값은 result이다. 리턴값인 result를 계산하는 부분은 다음과 같다. result = self.first + self.second

  • a.add()와 같이 a 객체에 의해 add 메서드가 수행되면 add 메서드의 self에는 객체 a가 자동으로 입력되므로 이 내용은 다음과 같이 해석된다. result = a.first + a.second

  • a.first와 a.second는 add 메서드가 호출되기 전에 a.setdata(4, 2) 문장에서 a.first = 4, a.second = 2로 설정된다. 따라서 위 문장은 다시 다음과 같이 해석된다. result = 4 + 2

따라서 다음과 같이 a.add()를 호출하면 6을 리턴한다.

>>> a.add()
6

여기까지 모두 이해하였다면 클래스에 대해 80% 이상을 안 것이다. 파이썬의 클래스는 그다지 어렵지 않다.


곱하기, 빼기, 나누기 기능 만들기
(Creating the Multiplication, Subtraction, and Division Functionalities)

mul, sub, div 모두 add 메서드에서 배운 것과 동일한 방법이므로 따로 설명하지는 않고 정말 모든 것이 제대로 동작하는지 확인해 보자.

class FourCal():
    def setdata(self, first, second):
        self.first = first
        self.second = second

    def add(self):
        result = self.first + self.second
        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

a = FourCal()
b = FourCal()

a.setdata(4,2)
b.setdata(3,6)

print("a.add():",a.add())
print("a.mul():",a.mul())
print("a.sub():",a.sub())
print("a.div():",a.div())

print("b.add():",b.add())
print("b.mul():",b.mul())
print("b.sub():",b.sub())
print("b.div():",b.div())
  • print() 없이 코드를 실행하면 마지막 연산 결과만 출력되기 때문에 각 연산 결과를 출력하려면 print 문을 사용해야 한다.

7️⃣ 생성자 (Constructor)

QUIZ