logoRawon_Log
홈블로그소개

Built with Next.js, Bun, Tailwind CSS and Shadcn/UI

Python

Python beginner - OOP

Rawon
2025년 9월 6일
목차
Python 기초 문법 - OOP
intro
Classes
Method
Inheritance(상속)
Recap

목차

Python 기초 문법 - OOP
intro
Classes
Method
Inheritance(상속)
Recap

Python 기초 문법 - OOP

intro

  • 객체지향 프로그래밍을 통해 데이터를 기반으로 동작하는 함수로 데이터를 캡슐화 할 수 있음
  • 예를 들어 비디오게임 소프트웨어를 만든다고 가정해보면
python
player = {
  "name" : "Jung",
  "XP" : 1000,
  "team" : "Team X"
}

def introduce_player(player):
  name = player["name"]
  team = player["team"]
  print(f"Hello My name is {name} and I play for {team}")
  
introduce_player(player)

# 위 예시에서는 함수와 데이터 구조가 개념적으로 연결되어 있지만 코드 상으로는 딕셔너리와 해당 딕셔너리를 print
# 하는 함수일 뿐, 서로 구분되어 있음
# 만약 플레이어를 추가하는 함수나 팀에 대한 딕셔너리를 만든다고 하면 코드의 복잡성이 증가할 것임.
  • OOP는 데이터를 어떻게 구조화해야하는지 알려주고
  • 그 데이터를 수정하기 위해 어디에 어떤 함수를 넣어야 하는지 명확한 경계를 만들어줌.

Classes

  • 데이터가 어떻게 생겨야하는지에 대한 청사진, 데이터의 구조를 정의할 수 있도록 해주며, 캡슐화가 가능하게 함
  • Class 생성 방법
python
class Puppy:
  pass
  
ruffus = Puppy()  # ruffus는 Puppy의 한 종류임을 정의, Puppy 객체의 한 종류

print(ruffus)  # ~~.Puppy object at 0x7~~

Method

  • 첫번째 규칙 : class 안에 있는 함수
  • 사용방법은 일반 함수와 동일함. 함수의 위치에 따라 class 내부에 있으면 method 가 됨.
  • class를 초기화하거나 만들기 위해서는 함수를 실행하는 것과 같이 소괄호 () 를 붙여주어야 함
  • 이렇게 하게되면 python 은 자동으로 __init__ 이라는 method를 호출함. 즉 객체가 생성될 때, 자동으로 호출되는 생성자 메서드
python
class Puppy:
  def __init__():
    print("Puppy is born")
  
ruffus = Puppy()

print(ruffus)

# 위 상태로 실행하면 에러가 발생하는데
# init 메서드는 Puppy()가 생성되며, 자동으로 python이 실행하는데
# 1개의 argument를 가지고 실행했으나 현재 init 함수에는 0개 parameter를 받고 있으므로 에러가 발생함.
  • 이를 통해 알 수 있는 method 의 두번째 규칙은
  • method를 가지고 있을 경우 기본적으로 method의 첫번째 argument는 self 가 되어야 함. 이건 모든 method에 자동으로 적용되는 규칙!
python
class Puppy:
  def __init__(potato):
	  print(potato)
    print("Puppy is born")
  
ruffus = Puppy()

print(ruffus)

# console 결과
# ~~.Puppy object at 0x7f5~
# Puppy is born!
# ~~.Puppy object at 0x7f5~
  • 위 예시에서 ruffus와 class method인 init의 첫번째 argument의 메모리 주솟값이 동일한 것을 볼 수 있는데,
  • 이것이 의미하는 바는 puppy 라는 class에 있는 모든 method는 첫번째 argument에서 자기 자신에 대한 참조를 갖고 있음! (위 예시에서는 potato 가 ruffus 를 의미하므로 같은 주소값을 갖음)
  • 아래와 같이 Puppy 클래스의 데이터를 커스터마이징하는데 유용하게 사용됨
python
class Puppy:
  def __init__(self):
	  self.name = "Ruffus"
	  self.age = 0.1
	  self.breed = "Beagle"
  
ruffus = Puppy()

print(ruffus.name, ruffus.age, ruffus.breed)  # Ruffus 0.1 Beagle
  • 위 코드의 문제로는 새로운 Puppy를 생성하더라도 모두 같은 이름, 나이, 종을 갖는다는 문제가 있음.
  • 좀 더 커스터마이징화 하기 위해 개선해보면
python
class Puppy:
  def __init__(self, name, breed):
	  self.name = name
	  self.age = 0.1
	  self.breed = breed
  
ruffus = Puppy(
  name ="Ruffus", breed="Beagle"
  )
bibi = Puppy(
  name="Bibi", breed="Dalmatian"
  )

print(ruffus.name, bibi.name)  # Ruffus Bibi

  • python은 class를 위한 정말 많은 밑줄을 활용한 method 가 있음.
  • 그 중 __str__ 은 python의 클래스 내장 메서드 중 하나로 인스턴스를 print 함수로 호출하게 되면 __str__ 의 리턴 값을 실행함
  • 인스턴스(instance)는 클래스의 객체, 즉 클래스(청사진)를 바탕으로 만들어진 실체를 의미함
python
class Puppy:
  def __init__(self, name, breed):
	  self.name = name
	  self.age = 0.1
	  self.breed = breed

  def __str__(self):
    return "Hello!"
  
ruffus = Puppy(
  name ="Ruffus", breed="Beagle"
  )
bibi = Puppy(
  name="Bibi", breed="Dalmatian"
  )

print(ruffus, bibi)  # Hello! Hello!
print(ruffus.breed, bibi.breed)  # Beagle, Dalmatian
  • __method__ 와 같이 기본 내장 메서드 외에도 내가 커스텀한 메서드를 사용해서 데이터에 기능성을 입힐 수 있음
python
class Puppy:
  def __init__(self, name, breed):
	  self.name = name
	  self.age = 0.1
	  self.breed = breed
	
	def woof_woof(self):
	  print("woof woof!")
	  
	def introduce(self):
	  self.woof_woof()
	  print(f"hello my name is {self.name} and i am baby {self.breed}")
	  self.woof_woof()
  
ruffus = Puppy(
  name ="Ruffus", breed="Beagle"
  )
bibi = Puppy(
  name="Bibi", breed="Dalmatian"
  )

print(ruffus.introduce)
# woof woof!
# hello my name is Ruffus and i am baby Beagle
# woof woof!

Inheritance(상속)

  • 상속(inheritance)은 코드를 저장하고 다시 사용할 수 있게 해줌.
  • 위 예시에서의 Puppy는 이름, 나이, 품종의 값을 가지고 있는데, 만약 다른 종류의 강아지 (예를 들어 경비견)에 대한 클래스를 만든다면 init 메서드를 정의하고 puppy 클래스를 만들 때 했던 작업을 그대로 반복해야 함.
python
class Guard_Dog:
  def __init__(self, name):
    self.name = name
    ~~~
  • 이런 경우 상속(inheritance)의 역할이 필요함. 상속을 통해 위와 같은 과정을 더는 반복하지 않을 수 있음
  • 상속 표현은 아래와 같이 자식 클래스에 소괄호()를 붙이고 내부에 부모 클래스명을 입력
python
class Dog:
  def __init__(self, name, age, breed):
    self.name = name
    self.age = age
    self.breed = breed
    
class Guard_Dog(Dog):

class Puppy(Dog):
  • 이렇게 함으로서 Guard_Dog 과 Puppy는 Dog 를 상속하며, 이를 통해 name, age, breed와 같은 공통 속성을 공유한다는 것을 알 수 있음
  • 아래 예시에서 super 는 Dog 인 부모 클래스를 참조하는 것을 의미함.
python
class Dog:
  def __init__(self, name, age, breed):
    self.name = name
    self.age = age
    self.breed = breed
    
  def sleep(self):
    print("zzzz")
    
class Guard_Dog(Dog):
  def __init__(self, name, breed):
    super().__init__(name, 5, breed)
  
  def grrr(self):
    print("grrr")  
    
    
class Puppy(Dog):
  def __init__(self, name, breed):
    super().__init__(name, 0.1, breed)
    self.aggresive = True
  
  def woof_woof(self):
    print("woof woof!")
    
 ruffus = Puppy(
	 name = "Ruffus",
	 breed = "Beagle"
 )
 
 rufus.woof_woof()
 rufus.sleep()
 rufus.grrr() # 에러 발생! grrr 메서드는 Guard_Dog 클래스에만 존재함.

Recap

  • 지금까지 배운 내용을 바탕으로 비디오 게임 플레이어 클래스를 만듦.
python
class Player:
  def __init__(self, name, team):
	  self.name = name
	  self.xp = 1500
	  self.team = team
	
	def introduce(self):
	  print(f"hello! i`m {self.name} and i play for {self.team}")

class Team:
  def __init__(self, team_name):
    self.team_name = team_name
    self.players = []
    
  def show_players(self):
    for player in self.players:
       player.introduce()
  
  def add_player(self, name):
    new_player = Player(name, self.team_name)
    self.players.append(new_player)


team_x = Team("Team X")
team_x.add_player("jung")

blue_team = Team("Team Blue")
team_blue.add_player("kim")

team_blue.show_players()  # hello! i`m kim and i play for Team Blue

이 링크를 통해 구매하시면 제가 수익을 받을 수 있어요. 🤗

https://inf.run/Trxxf