OOP 객체 지향 프로그래밍

이다연·2021년 1월 27일
0

OOP

목록 보기
2/3

From Codeit 객체 지향 프로그래밍
Angela Day 39 에서 OOP가 헷갈려서 다시 공부하기 위해 들음.

Chapter 1: 객체 지향 프로그래밍 시작하기

객체 지향 프로그래밍: 프로그램을 여러 개의 독립된 객체들과 그 객체들 간의 상호작용으로 파악하는 프로그래밍 접근법.

프로그램을 객체들과 객체들 간 소통으로 바라보는 것.

모델링

객체 지향 프로그래밍을 만들려면,

  1. 어떤 객체들이 필요할지 정한다.
  2. 객체들의 속성과 행동을 정한다.
  3. 객체들이 서로 어떻게 소통할지 정한다.

Chapter 2: 객체를 만드는 법

  • 클래스: 설계도로 객체를 만든다.

  • 객체: 클래스를 활용해 인스턴스 여러개를 만들 수 있다.

  • 속성: 변수와 같이 사용

Class User:
	pass
    
    
user1 = User()
user2 = User()

user1.name = "철수"
user1.email = "chch@email.com"

user2.name = "영희"
user2.email = "yhyh@email.com"
  • 메소드: 행동

1. 인스턴스 메소드: 인스턴스 변수를 사용하거나, 인스턴스 변수에 값을 설정하는 메소드

Class User:
	def say_hello(some_user):
    	#인사 메세지 출력 메소드
    	print(f"안녕하세요 저는 {some_user.name}입니다!")
    
user1.name = "철수"
user1.email = "chch@email.com"

user2.name = "영희"
user2.email = "yhyh@email.com"


#------------------------------------------------
#some_user => user1, user2 .... intances' name

#1 Class.method(instance)

User.say_hello(user1) 


#2 instance.method 

user1 = User()
user1.say_hello()

특별한 규칙!

2번과 같이 instance.method: say_hello(some_user) 파라미터로 user1 이 some_user 인자에 자동으로 할당됨.

파이썬에서는 인스턴스 메소드 첫번째 파라미터 이름을 "self"로 쓰라고 권장.
결국, 인스턴스 자신이 첫번째 파라미터로 들어가는 것이니깐. '나자신' 이라고 써주는 것.

  • 특수 메소드: (Magic method/ special method) 특정 상황에서 자동으로 호출되는 메소드
    __init__: 인스턴스가 생성될 때 자동으로 호출
def initialize(self, name, password):
	self.name = name
    self.password = pasword

user1 = User()
user1.initialize("YH", "1234")

#init method is an initializer 

def __init__(self, name, password):
	self.name = name
    self.password = pasword

user1 = User("YH", "1234")

Task. Instagram follow

follow 함수에서 인자로 self, another_user 처럼 객체만 넣어주면 동작은 하지만, 리스트를 반환하고 싶을 때 객체의 메모리 주소가 나오게 된다. self.name, another_user.name 처럼 인수를 넣어야함. -> 객체.name 을 append해야 이름이 출력된다.

class User:
    # 인스턴스 변수 설정
    def __init__(self, name, email, password):
        self.name = name
        self.email = email
        self.password = password

        self.following_list = []    # 이 유저가 팔로우하는 유저 리스트
        self.followers_list = []    # 이 유저를 팔로우하는 유저 리스트

    # 팔로우
    def follow(self, another_user):
        self.following_list.append(another_user.name)
        another_user.followers_list.append(self.name)
        
        #-> self 도 another_user도 동등한 파라미터!!!! 인스턴스를 만들었을 때 self와 another_user 라는 라벨을 보고 서로 다른 객체로서 구분할 수 있게 된다. 


    # 내가 몇 명을 팔로우하는지 리턴
    def num_following(self):
        return len(self.following_list)

    # 나를 몇 명이 팔로우하는지 리턴
    def num_followers(self):
        return len(self.followers_list)

# 유저들 생성
user1 = User("Young", "young@codeit.kr", "123456")
user2 = User("Yoonsoo", "yoonsoo@codeit.kr", "abcdef")
user3 = User("Taeho", "taeho@codeit.kr", "123abc")
user4 = User("Lisa", "lisa@codeit.kr", "abc123")

# 유저마다 서로 관심 있는 유저를 팔로우
user1.follow(user2)
user1.follow(user3)
user2.follow(user1)
user2.follow(user3)
user2.follow(user4)
user4.follow(user1)

# 유저 이름, 자신의 팔로워 수, 자신이 팔로우하는 사람 수를 출력합니다
print(user1.name, user1.num_followers(), user1.num_following(), user1.following_list)
print(user2.name, user2.num_followers(), user2.num_following())
print(user3.name, user3.num_followers(), user3.num_following())
print(user4.name, user4.num_followers(), user4.num_following())

#printed
Young 2 2 ['Yoonsoo', 'Taeho']
Yoonsoo 1 3
Taeho 2 0
Lisa 1 1

__str__ 던더 에스티알, 특수상황: 프린트 함수를 호출할 때 자동으로 불러짐

def __str__(self):
	return f"사용자: {self.name}, 비밀번호:{self.password}"
    
user1 = User("Kim", "1234")
print(user1)
#printed
사용자: Kim, 비밀번호:1234

---------------다시 공부--------------

  • 클래스 변수: 여러 인스턴스들이 공유하는 속성 값
    값 설정: 클래스이름.클레스변수 이름

데코레이터 함수
파라미터로 함수를 받음

@classmethod  -> 기존 함수에 새로운 기능 추가!
def function(): 
	pass

2. 클래스 메소드: 클래스 변수의 값을 읽거나 설정하는 메소드

class User:
	count = 0

@classmethod
def number_of_users(cls):   #cls.count <-> User.count
	print(cls.count)

#1. Class.method
User.number_of_users()

#2. instance.method
user1.number_of_users() 

=> 같은 결과

Q클래스 변수와 인스턴스 변수를 둘 다 쓴다면?
인스턴스 매소드. 클래스 메소드는 인스턴스 변수 사용 불가.
Q인스턴스 없어도 필요한 정보가 있다면?

Chapter 3: 미리 알고가야 할 것들

파이썬은 순수 객체 지향 언어: 파이썬의 모든 것이 객체
파이썬의 모든 것은 어떤 클래스의 인스턴스 이다.
우리도 모르게 미리 쓰여진 클래스들을 사용하고 있었음

print(type(user1)) -> <class '__main__.User'>
print(type(2)) ->  <class 'int'>
  • 가변 vs 불변
    mutable 가변 타입 객체: 한번 생성한인스턴스의 속성 변경 가능 e.g. 리스트, 디셔너리, 직접 작성하는 클래스
    immutable 불변 타입 객체: 한번 생성한 인스턴스의 속성 변경 불가 e.g. 튜플, 불, float, str, tuple

-> 같은 상황에서 다른 결과를 낼 수 있음

mutable = [1, 2, 3]
mutable[0] = 4
[4, 2, 3]

tuple
immutable = (1, 2, 3)
immutable[0] = 7 -> error
immutable = (2, 3, 4)
다른 값을 할당해서 아예 새로운 튜플 인스턴스 생성.  

Chapter 4: 객체 만들기 연습

Chapter 5: 객체 지향 프로그래밍 직접 해보기
profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글