(Python 4-1๊ฐ) Python Object Oriented Programming
210803
๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ ๊ฐ์
Object-Oriented Programming, OOP
๊ฐ์ฒด: ์ค์ํ์์ ์ผ์ข ์ ๋ฌผ๊ฑด
์์ฑ(Attribute)๊ณผ ํ๋(Action)์ ๊ฐ์ง
ํ์ด์ฌ ์ญ์ ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋จ ์ธ์ด
ํด๋์ค ์ ์ธ
class ์ ์ธ, object๋ python3์์ ์๋ ์์
class SoccerPlayer(object):
# class : class ์์ฝ์ด
# SoccerPlayer : class ์ด๋ฆ
# (object) : ์์๋ฐ๋ ๊ฐ์ฒด๋ช
๋ช ๋ช ๋ฒ์ด ์กด์ฌ
ํ์ด์ฌ ํจ์/๋ณ์๋ช ์๋ snake_case๋ฅผ ์ฌ์ฉ
Class๋ช ์ CamelCase๋ฅผ ์ฌ์ฉ
์์
๋ถ๋ชจํด๋์ค๋ก๋ถํฐ ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ๋ฌผ๋ ค๋ฐ์ ์์ํด๋์ค๋ฅผ ์์ฑํ๋ ๊ฒ
๋คํ์ฑ
๊ฐ์ ์ด๋ฆ ๋ฉ์๋์ ๋ด๋ถ ๋ก์ง์ ๋ค๋ฅด๊ฒ ์์ฑ
Dynamic Typing ํน์ฑ์ผ๋ก ์ธํด ํ์ด์ฌ์์๋ ๊ฐ์ ๋ถ๋ชจํด๋์ค์
์์์์ ์ฃผ๋ก ๋ฐ์ํจ
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print(animal.name + ': ' + animal.talk())
๊ฐ์์ฑ
๊ฐ์ฒด์ ์ ๋ณด๋ฅผ ๋ณผ ์ ์๋ ๋ ๋ฒจ์ ์กฐ์ ํ๋ ๊ฒ
๋๊ตฌ๋ ๊ฐ์ฒด ์์ ๋ชจ๋ ๋ณ์๋ฅผ ๋ณผ ํ์๊ฐ ์์
1) ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ์ฌ์ฉ์๊ฐ ์์๋ก ์ ๋ณด ์์
2) ํ์ ์๋ ์ ๋ณด์๋ ์ ๊ทผ ํ ํ์๊ฐ ์์
3) ๋ง์ฝ ์ ํ์ผ๋ก ํ๋งคํ๋ค๋ฉด? ์์ค์ ๋ณดํธ
First-class objects
์ผ๋ฑํจ์ ๋๋ ์ผ๊ธ ๊ฐ์ฒด
๋ณ์๋ ๋ฐ์ดํฐ ๊ตฌ์กฐ์ ํ ๋น์ด ๊ฐ๋ฅํ ๊ฐ์ฒด
ํ๋ผ๋ฉํฐ๋ก ์ ๋ฌ์ด ๊ฐ๋ฅ + ๋ฆฌํด ๊ฐ์ผ๋ก ์ฌ์ฉ
ํ์ด์ฌ์ ํจ์๋ ์ผ๊ธํจ์์ด๋ค
Inner function
ํจ์ ๋ด์ ๋ ๋ค๋ฅธ ํจ์๊ฐ ์กด์ฌ
def print_msg(msg):
def printer():
print(msg)
printer()
print_msg("Hello, Python")
closures
inner function์ return๊ฐ์ผ๋ก ๋ฐํ
def print_msg(msg):
def printer():
print(msg)
return printer
another = print_msg("Hello, Python")
another()
Last updated
Was this helpful?