새로새록
[python]0723 본문
>라이브러리
Seaborn 라이브러리 - ttps://seaborn.pydata.org/tutorial.html
Pandas 라이브러리 - https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html
구글에 best Practice라는 키워드로 검색
>개발 문서
몇 가지 언어의 공식 사이트 링크를 공유드립니다.
Python - https://docs.python.org/ko/3/
Javascript - https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide
Ruby- https://www.ruby-lang.org/ko/documentation/
Java- https://docs.oracle.com/en/java/
>>데코레이터 함수
def add_print_to(original):
def wrapper():
print("함수시작작")
original()
print("함수끝")
return wrapper
---------------------
---------------------
print_hello=add_print_to(print_hello)
print_hello()
---------------------
#이 대신에 애초에 print_hello()를 정의할적에 보내준다고 신호를 줘도 됨
#정의부에서 선언을 해주면, 새로적용해줄 필요가 없음
@add_print_to
def print_hello():
print("안녕하세요")
print_hello()
---------------------
---------------------
>>인스턴스메소드
파라미터 값: self
>>클래스메소드
클래스 첫번째 파라미터의 값으로는 cls를 써주기
@classmethod
def number_of_users(cls):
print("총 유저의 수는: {}입니다.".format(cls.count))
인스턴스로 호출:
User,say_hello(user1)
user1.say_hello() #이 경우만 자신이 첫번째 파라미터로 자동전달
클래스로 호출
User.number_of_users()
user1.number_of_users)() #둘다 첫번째 파라미터로 자동전달
-클래스변수와 인스턴스 변수 모두 쓴다면: 인스턴스 메소드
-왜 클래스 메소드로 만든걸까?
-인스턴스 변수를 안 쓰기 때문!
-인스턴스메소드: 인스턴스(self)와 클래스(000.000) 변수 모두 가능
-클래스 메소드: 인스턴스 변수 사용 불가
-인스턴스 없이도 필요한 정보가 있다면 클래스 메소드를 사용해야 한다.
-인스턴스 메소드와 달리 클래스 메소드는 특정 인스턴스에 접근할 수 없습니다.
class User:
-인스턴스메소드: def ~~(self): print(~~{}~~.format(self.~~))
-클래스메소드: def ~~(cls): print(~~{}~~.format(cls.~~))
-클래스를 인스턴스메소드: def ~~(self): print(~~{}~~.format(User.00))
>정적 메소드는 같은 자동 전달되는 파라미터가 없습니다.
인스턴스, 클래스 두 가지 모두를 통해 사용 가능합니다.
class GameCharacter:
# 게임 캐릭터 클래스
def __init__(self, name, hp, power):
# 게임 캐릭터는 속성으로 이름, hp, 공격력을 갖는다
self.name = name
self.hp = hp
self.power = power
def is_alive(self):
# 게임 캐릭터가 살아있는지(체력이 0이 넘는지) 확인하는 메소드
return self.hp>0
def get_attacked(self, damage):
if self.is_alive():
self.hp = self.hp - damage if self.hp >= damage else 0
else:
print("{}은 이미 죽었습니다.".format(self.name))
"""
게임 캐릭터가 살아있으면 공격한 캐릭터의 공격력만큼 체력을 깎는 메소드
조건:
1. 이미 캐릭터가 죽었으면 죽었다는 메시지를 출력한다
2. 남은 체력보다 공격력이 더 크면 체력은 0이 된다.
"""
def attack(self, other_character):
# 게임 캐릭터가 살아있으면 파라미터로 받은 다른 캐릭터의 체력을 자신의 공격력만큼 깎는다.
if self.is_alive():
other_character.get_attacked(self.power)
def __str__(self):
return "{}님의 hp는 {}만큼 남았습니다.".format(self.name, self.hp)
# 게임 캐릭터의 의미있는 정보를 포함한 문자열을 리턴한다.
# 게임 캐릭터 인스턴스 생성
character_1 = GameCharacter("Ww영훈전사wW", 200, 30)
character_2 = GameCharacter("Xx지웅최고xX", 100, 50)
# 게임 캐릭터 인스턴스들 서로 공격
character_1.attack(character_2)
character_2.attack(character_1)
character_2.attack(character_1)
character_2.attack(character_1)
character_2.attack(character_1)
character_2.attack(character_1)
# 게임 캐릭터 인스턴스 출력
print(character_1)
print(character_2)
class Post:
# 게시글 클래스
def __init__(self, date, content):
# 게시글은 속성으로 작성 날짜와 내용을 갖는다
self.date = date
self.content = content
def __str__(self):
# 게시글의 정보를 문자열로 리턴하는 메소드
return "작성 날짜: {}\n내용: {}".format(self.date, self.content)
class BlogUser:
# 블로그 유저 클래스
def __init__(self, name):
"""
블로그 유저는 속성으로 이름, 게시글들을 갖는다
posts는 빈 배열로 초기화한다
"""
self.name = name
self.posts = []
def add_post(self, date, content):
# 새로운 게시글 추가
new_post = Post(date, content)
self.posts.append(new_post)
def show_all_posts(self):
# 블로그 유저의 모든 게시글 출력
for post in self.posts:
print(post)
def __str__(self):
# 간단한 인사와 이름을 문자열로 리턴
return "안녕하세요 {}입니다.\n".format(self.name)
# 블로그 유저 인스턴스 생성
blog_user_1 = BlogUser("성태호")
# 블로그 유저 인스턴스 출력(인사, 이름)
print(blog_user_1)
# 블로그 유저 게시글 2개 추가
blog_user_1.add_post("2019년 8월 30일", """
오늘은 내 생일이였다.
많은 사람들이 축하해줬다.
행복했다.
""")
blog_user_1.add_post("2019년 8월 31일", """
재밌는 코딩 교육 사이트를 찾았다.
코드잇이란 곳인데 최고다.
같이 공부하실 분들은 www.codeit.kr로 오세요!
""")
# 블로그 유저의 모든 게시글 출력
blog_user_1.show_all_posts()
# 블로그 유저 게시글 2개 추가
blog_user_1.add_post("2019년 8월 30일", """
오늘은 내 생일이였다.
많은 사람들이 축하해줬다.
행복했다.
""")
blog_user_1.add_post("2019년 8월 31일", """
재밌는 코딩 교육 사이트를 찾았다.
코드잇이란 곳인데 최고다.
같이 공부하실 분들은 www.codeit.kr로 오세요!
""")
# 블로그 유저의 모든 게시글 출력
blog_user_1.show_all_posts()
인스턴스 메소드에서 다른 클래스의 인스턴스 생성하기
add_post 메소드는 인스턴스 변수 posts에 새로운 게시글을 추가합니다. 그런데 파라미터로 Post 클래스의 인스턴스가 바로 넘어오지는 않네요. 하지만
- 작성 날짜
- 내용
을 파라미터로 받는군요. 이 파라미터를 사용해 게시글 인스턴스를 직접 생성하면 되겠죠?
def add_post(self, date, content):
# 새로운 게시글 추가
new_post = Post(date, content)
# 인스턴스 변수 posts에 new_post를 추가한다
'소프트웨어융합' 카테고리의 다른 글
seaborn - 함수 /catplog카테고리별 시각화 (0) | 2021.07.23 |
---|---|
chap2 코코스 외계인게임 (2) | 2020.10.07 |
[파이썬]코딩도장-오각별, 육각별 (0) | 2020.07.01 |
[파이썬]코딩도장-공배수처리하기 (0) | 2020.06.30 |
[파이썬]코딩도장 - 산모양 별 출력 (0) | 2020.06.30 |