해당 게시글은 개인적인 학습 목적의 글입니다.
게시글 내 모든 정보 출처: 🔗 인프런 강의
ctrl + bctrl + jctrl + shift + xctrl + ,ctrl + shift + ppython : Python 설치가 잘 되었는지 확인 & 콘솔창 실행pip : pip 확인pip list : 현재 설치된 파이썬 패키지를 확인할 수 있다.python [파일명.py] : 해당 파일을 실행시킨다.python -m venv [가상환경 이름-통상적으로 venv] : 가상 환경 생성source [venv]/bin/activate : 가상환경 venv 접속.[venv]\Scripts\Activate.ps1[venv]\Scripts\activate.batdeactivate: 가상환경 venv 나가기.black 사용ctrl + ,) Editor: Default Formatter를 Python으로 변경ctrl + shift + p 누르고 Select Interpreter 입력하여, 인터프리터 변경which python 입력 후 경로 복사하여 위 검색창에 붙여놓고 클릭 (2번 실행)where python 입력 후 경로 복사하여 위 검색창에 붙여놓고 클릭 (2번 실행)use black 클릭ctrl + ,) 열고 python formatting provider 검색 후 black으로 변경!flake8 사용ctrl + shift + p 누르고 python: Select Linter 입력flake8 선택 (종류는 다양하다.) -> 종류 별 차이점 찾아보자.pip는 파이썬으로 작성된 패키지, 라이브러리, 프레임워크를 관리해주는 툴이다.
pip install pip --upgrade : pip 업그레이드pip install "패키지~=3.0.0" : 3.0.0 버전의 패키지를 설치한다.pip install [패키지] : 패키지를 설치한다.pip uninstall [패키지]: 패키지를 삭제한다.pip --version : 설치된 pip 버전을 확인할 수 있다.pip freeze : 설치된 패키지를 확인할 수 있다.pip freeze > requirements.txt : requirements.txt파일에 설치된 패키지를 출력한다.pip install -r requirements.txt : requirements.txt파일에 기록된 패키지를 설치한다.추가적으로 requirements.txt에 주석으로 Python version도 명시해주면 좋다.
# 적용 전
def copyright(func):
def new_func():
print("@Copyright")
func()
return "end!"
return new_func
def smile():
print("😊")
def sunglass():
print("😎")
def angry():
print("🤬")
def doggy():
print("🐶")
def madness():
print("👹")
def scary():
print("😫")
def hmm():
print("🤔")
def surprise():
print("😨")
# 새로운 함수로 재정의 해준다. 이 때, 각 object는 새로운 함수로 재정의 된다.
# 예를 들어, smile의 경우 copyright()로 재정의 된다.
# 이때 smile은 재정의된 함수다.
# Python에선 소괄호 ()를 붙일 경우 실행하라는 뜻이 되어,
# smile()을 인자로 넘기면
# smile()의 return 값인 None이 인자로 넘어가 not callable 오류가 발생한다.
smile = copyright(smile)
sunglass = copyright(sunglass)
angry = copyright(angry)
doggy = copyright(doggy)
madness = copyright(madness)
scary = copyright(scary)
hmm = copyright(hmm)
surprise = copyright(surprise)
smile()
sunglass()
angry()
doggy()
madness()
scary()
hmm()
surprise()
print(smile)
# 함수 자체를 print하면 smile이 먼저 실행되고 -> copyright(smile)
# 해당 함수의 return 값을 print한다.
# 여기에선 copyright의 return 값이 없으므로 None 이 찍힌다.
# 현재는 return 값을 end! 로 지정하여, end! 가 찍힌다.
print(smile())
def copyright(func):
def new_func():
print("@Copyright")
func()
return "end!"
return new_func
# Decorator 적용!
@copyright
def smile():
print("😊")
@copyright
def sunglass():
print("😎")
@copyright
def angry():
print("🤬")
@copyright
def doggy():
print("🐶")
@copyright
def madness():
print("👹")
@copyright
def scary():
print("😫")
@copyright
def hmm():
print("🤔")
@copyright
def surprise():
print("😨")
smile()
sunglass()
angry()
doggy()
madness()
scary()
hmm()
surprise()
Object Oriented Programming캡슐화(Encapsulation): 객체의 속성과 행위를 하나로 묶고, 구현된 일부를 감추어 은닉한다.추상화(Abstraction): 불필요한 정보는 숨기고 필요한 정보만을 표현함으로써 공통의 속성이나 행위를 하나로 묶어 이름을 붙이는 것상속(Inheritance): 부모의 속성과 행위를 물려받은 자식은 이를 재정의하여 사용할 수 있다.다형성(Polymorphism): 여러 형태를 가질 수 있도록 한다. 즉, 객체를 부품화할 수 있도록 한다.def plus(a, b):
return a + b
def minus(a, b):
return a - b
def multiple(a, b):
return a * b
def divide(a, b):
return a / b
print(plus(1, 2))
print(multiple(1, 2))
class Calculator:
# 생성자 : 메모리에 올라오는 즉시 실행된다.
def __init__(self, a, b):
self.a = a
self.b = b
# 인스턴스 메서드
def plus(self):
return self.a + self.b
def minus(self):
return self.a - self.b
def multiple(self):
return self.a * self.b
def divide(self):
return self.a / self.b
# 아래와 같이 생성하며, 생성 시 self는 instance인 calculator1로,
# a는 1, b는 2로 할당된다.
# 또한 생성자에서 정의한 self.a 는 인스턴스 변수가 되며,
# 이때 파라미터로 받은 a를 할당하는 것이다.
calculator1 = Calculator(1, 2)
calculator2 = Calculator(3, 4)
print(calculator1.a)
print(calculator1.b)
print(calculator1.plus())
print(calculator1.multiple())
print(calculator2.a)
print(calculator2.b)
print(calculator2.plus())
print(calculator2.multiple())
# 아래와 같이 할당된 인스턴스 변수여도 재할당이 가능하다.
calculator2.a = 9
__init__(self) 와 같은 이름으로 지정되며, # abstraction : 추상화
class Robot:
# 클래스 변수 : 인스턴스들이 공유하는 변수
population = 0
# 생성자 함수 : 인스턴스가 생성될 때 초기화가 되는 함수
def __init__(self, name, code):
self.name = name # 인스턴스 변수
self.code = code # 인스턴스 변수
# 모든 인스턴스들이 공유하는 클래스 변수의 값을, 생성될 때 마다 + 1 씩 해준다.
Robot.population += 1
# 인스턴스 메서드
def say_hi(self):
# code..
print(f"Greetings, my masters call me {self.name}.")
# 인스턴스 메서드
def calc_add(self, a, b):
return a + b
# 인스턴스 메서드
def die(self):
print(f"{self.name} is being destroyed!")
# 죽었을 경우 클래스 변수인 population 1 감소
Robot.population -= 1
if Robot.population == 0:
print(f"{self.name} was the last one.")
else:
print(f"There are still {Robot.population} robots working.")
# 인스턴스 메서드
def fixed(self):
print(f"{self.name} is fixed now!")
# 고쳤을 경우 클래스 변수인 population 1 증가
Robot.population += 1
print(f"There are {Robot.population} robots working now.")
# 클래스 메서드
@classmethod
def how_many(cls): # cls는 인스턴스인 self 대신 클래스를 받는 것 (class를 의미).
print(f"We have {cls.population} robots.")
print(Robot.population) # 0
siri = Robot("siri", 120392491)
jarvis = Robot("jarvis", 1232349729)
bixby = Robot("bixby", 3452234134435)
print(Robot.population) # 3
print(siri.name)
print(siri.code)
siri.calc_add(2, 3)
siri.die()
Robot.how_many()
siri.fixed()
Robot.how_many()
추상화)@classmethod를 붙여 사용한다.self라는 인스턴스를 받는 예약어 대신, cls라는 예약어를 사용한다.매직 메서드들
__dict__: 네임 스페이스를 확인할 수 있다.dir(): 네임 스페이스의 key 값을 확인할 수 있다.__doc__: class의 주석을 확인한다.__class__: 어떤 클래스로 만들어진 인스턴스인지 확인할 수 있다.
class Robot:
# ... 위 코드와 동일하여 생략.
siri = Robot("siri", 120392491)
jarvis = Robot("jarvis", 1232349729)
bixby = Robot("bixby", 3452234134435)
# 클래스의 네임스페이스에는 인스턴스 메서드까지 저장되어있는 것을 확인할 수 있다.
print(Robot.__dict__)
"""
{'__module__': '__main__', 'population': 3,
'__init__': <function Robot.__init__ at 0x000002CE9B24BA30>,
'say_hi': <function Robot.say_hi at 0x000002CE9B24BAC0>,
'calc_add': <function Robot.calc_add at 0x000002CE9B24BB50>,
'die': <function Robot.die at 0x000002CE9B24BBE0>,
'fixed': <function Robot.fixed at 0x000002CE9B24BC70>,
'how_many': <classmethod(<function Robot.how_many at 0x000002CE9B24BD00>)>,
'__dict__': <attribute '__dict__' of 'Robot' objects>,
'__weakref__': <attribute '__weakref__' of 'Robot' objects>, '__doc__':None}
"""
# 인스턴스의 네임스페이스에는 인스턴스 변수만 저장된 것을 알 수 있다.
print(siri.__dict__)
print(jarvis.__dict__)
"""
{'name': 'siri', 'code': 120392491}
{'name': 'jarvis', 'code': 1232349729}
"""
# 파이썬에서 인스턴스는 클래스 변수와 클래스 메서드에 접근이 가능하다!!
print(siri.population)
siri.how_many()
# 클래스 자체로 인스턴스 메서드를 사용할 수 없지만,
# 인자로 인스턴스를 넘겨주면 사용 가능하다!
# 아래 두 줄의 코드는 동일한 기능을 수행한다.
Robot.say_hi(siri)
siri.say_hi()
# dir() : 사용할 수 있는 모든 변수, 메서드의 키 값을 출력해준다.
print(dir(siri))
"""
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'calc_add', 'code', 'die',
'fixed', 'how_many', 'name', 'population', 'say_hi']
"""
# __doc__ : class의 주석을 확인할 수 있다.
print(Robot.__doc__)
"""
[Robot Class]
Author: 김형준
Role: ~~~
"""
# __class__ : 해당 인스턴스가 어떤 클래스인지 확인할 수 있다.
print(siri.__class__)
# <class '__main__.Robot'>
class Robot:
# 클래스 변수 : 인스턴스들이 공유하는 변수
population = 0
# 생성자 함수 : 인스턴스가 생성될 때 초기화가 되는 함수
def __init__(self, name, code):
self.name = name # 인스턴스 변수
self.code = code # 인스턴스 변수
Robot.population += 1
# ... 생략
# 아래와 같이 데코레이터를 사용한다.
@staticmethod
def is_this_Robot():
return "Yes!, this is Robot!!"
siri = Robot("siri", 123123132)
print(siri.is_this_Robot())