PYTHON 객체

속성과 행동을 떠올릴 수 있다면 모두 객체이다. 객체는 속성과 행동으로 이루어져 있다. 속성은 변수로 나타내며, 행동은 함수(메소드)로 나타낸다.

객체란

객체 지향 프로그래밍

프로그램을 여러개의 독립된 __객체들과 그 객체들 간의 상호 작용__으로 파악하는 프로그래밍 접근법. 프로그램을 객체와 객체의 소통으로 바라본다. 프로그램에 어떤 객체들이 필요할지 정한 후에 속성과 행동을 정하고 서로 어떻게 소통할지 판단한다.

모델링(modeling) : 객체지향적으로 설계

꼭 알아야 할 4가지 개념 : 추상화 캡슐화, 상속, 다형성

객체 설계의 원칙, SOLID 원칙

  1. 단일 책임 원칙 (Single Responsibility Principle)
  2. 개방 폐쇄 원칙 (Open-closed Principle)
  3. 리스코프 치환 원칙 (Liskov Substitution Principle)
  4. 인터페이스 분리 원칙 (Interface Segregation Principle)
  5. 의존 관계 역전 원칙 (Dependency Inversion Principle)

클래스와 인스턴스

클래스는 어떠한 변수와 메소드를 가지는지 알려주는 명세서같은 설계도라고 보면 된다. 객체의 경우 클래스로 구현하고 싶은 결과물이며, 인스턴스로 실체화한다.

1
2
3
4
5
6
class User:
pass

User1 = User() # 유저 인스턴스가 생성된다.
User2 = User()
User3 = User()

인스턴스 변수

인스턴스가 개인적으로 갖고 있는 속성.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
user1.name = "Minjee Kim"
user1.email = "mjaedot@gmail.com"
user1.nickname = "mjaedot"

user2.name = "Inho Baek"
user2.email = "Inho@gmail.com"
user2.nickname = "cheese in the trap"

user3.name = "Myungyoung Gang"
user3.email = "hope@gmail.com"
user3.nickname = "Gadam Hangsul"

print(user1.name) # Minjee Kim
print(user2.email) #Inho@gmail.com
print(user3.age) #정의하지 않았으므로 에러 발생

메소드

  1. 인스턴스 메소드 : 인스턴스 변수를 사용하거나 인스턴스 변수에 값을 설정하는 메소드.
  2. 클래스 메소드
  3. 정적 메소드
1
2
3
4
5
6
7
class User:
def say_hello(some_user):
print("Hello, my name is {}.".format(some_user.name))

User.say_hello(user1) # Hello, my name is Minjee Kim.
User.say_hello(user2) # Hello, my name is Inho Baek.
User.say_hello(user3) # Hello, my name is Myungyoung Gang.

인스턴스 메소드의 특별한 규칙

1
2
3
#인스턴스의 메소드를 호출. 첫번째 파라미터를 자동으로 넣어준다.
user1.say_hello() # Hello, my name is Minjee Kim.
user1.say_hello(user1) # 파라미터가 2개 들어가게 되어 에러 발생.

self

파이썬에서는 인스턴스 메소드의 첫번째 파라미터를 self로 사용하는 것을 권장한다.

1
2
3
4
5
def login(self, my_email, my_nickname):
if(self.email == my_email and self.nickname == my_nickname):
print("환영합니다.")
else:
print("실패!")

인스턴스 변수와 같은 이름을 갖는 파라미터

1
2
3
4
5
6
def check_name(self, name):
# 파라미터로 받는 name이 유저의 이름과 같은지 불린값으로 리턴하는 메소드.
return self.name == name

print(user1.check_name("Minjee Kim")) # true
print(user1.check_name("Inho Baek")) # false

인스턴스 변수 초기값 선언

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class User:
def initialize(self, name, email, password):
self.name = name
self.email = email
self password = password

user1 = User()
user1.initialize("Young", "young@codeit.kr", "123456")
# Young young@codeit.kr 123456

user2 = User()
user2.initialize("Yoonsoo", "yoonsoo@codeit.kr", "abcdef")
# Yoonsoo yoonsoo@codeit.kr abcdef

user3 = User()
User.initialize(user3, "Taeho", "taeho@codeit.kr", "123abc")
# Taeho taeho@codeit.kr 123abc

user4 = User()
User.initialize(user4, "Lisa", "lisa@codeit.kr", "abc123")
# Lisa lisa@codeit.kr abc123

__init__ 메소드

__init__ 메서드는 인스턴스가 생성될 때 자동으로 호출된다.

  1. User 인스턴스 생성
  2. __init__ 메소드 자동 호출
  3. 인스턴스 변수들의 초깃값 설정

특수메소드 : 특정 상황에서 자동으로 호출되는 메소드(언더바가 두개씩 있는 메소드. magic method, special method)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class User:
def initialize(self, name, email, password):
self.name = name
self.email = email
self password = password

user1 = User("Young", "young@codeit.kr", "123456")
# Young young@codeit.kr 123456

user2 = User("Yoonsoo", "yoonsoo@codeit.kr", "abcdef")
# Yoonsoo yoonsoo@codeit.kr abcdef

user3 = User("Taeho", "taeho@codeit.kr", "123abc")
# Taeho taeho@codeit.kr 123abc

user4 = User("Lisa", "lisa@codeit.kr", "abc123")
# Lisa lisa@codeit.kr abc123

__str__ 메소드

인스턴스를 출력할 때 우리가 원하는 정보를 나오게 하고 싶다면 클래스에 __str__ 메소드를 정의하면 된다.

double underscore : dunder라고 부르기도 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class User:
def __init__(self, name, email, password):
self.name = name
self.email = email
self password = password

def sya_hello(self):
print("Hello, my name is {}.".format(self.name))

def __str__(self):
return "사용자: {}, 이메일: {}, 비밀번호: *****".format(self.name, self.email)

user1 = User("Minjee Kim", "mjaedot@gmail.com", "1234")
user1 = User("Inho Baek", "inho@gmail.com", "abcd")

print(user1)
print(user2)

REFERENCE
코드잇 온라인 강의 객체지향 프로그래밍

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer