player = {
"name" : "Jung",
"XP" : 1000,
"team" : "Team X"
}
def introduce_player(player):
name = player["name"]
team = player["team"]
print(f"Hello My name is {name} and I play for {team}")
introduce_player(player)
# 위 예시에서는 함수와 데이터 구조가 개념적으로 연결되어 있지만 코드 상으로는 딕셔너리와 해당 딕셔너리를 print
# 하는 함수일 뿐, 서로 구분되어 있음
# 만약 플레이어를 추가하는 함수나 팀에 대한 딕셔너리를 만든다고 하면 코드의 복잡성이 증가할 것임.
class Puppy:
pass
ruffus = Puppy() # ruffus는 Puppy의 한 종류임을 정의, Puppy 객체의 한 종류
print(ruffus) # ~~.Puppy object at 0x7~~
class
안에 있는 함수class
내부에 있으면 method
가 됨.class
를 초기화하거나 만들기 위해서는 함수를 실행하는 것과 같이 소괄호 ()
를 붙여주어야 함python
은 자동으로 __init__
이라는 method
를 호출함. 즉 객체가 생성될 때, 자동으로 호출되는 생성자 메서드
class Puppy:
def __init__():
print("Puppy is born")
ruffus = Puppy()
print(ruffus)
# 위 상태로 실행하면 에러가 발생하는데
# init 메서드는 Puppy()가 생성되며, 자동으로 python이 실행하는데
# 1개의 argument를 가지고 실행했으나 현재 init 함수에는 0개 parameter를 받고 있으므로 에러가 발생함.
method
의 두번째 규칙은method
를 가지고 있을 경우 기본적으로
method
의 첫번째 argument
는 self
가 되어야 함. 이건 모든 method
에 자동으로 적용되는 규칙!class Puppy:
def __init__(potato):
print(potato)
print("Puppy is born")
ruffus = Puppy()
print(ruffus)
# console 결과
# ~~.Puppy object at 0x7f5~
# Puppy is born!
# ~~.Puppy object at 0x7f5~
ruffus
와 class
method
인 init
의 첫번째 argument
의 메모리 주솟값이 동일한 것을 볼 수 있는데,puppy
라는 class
에 있는 모든 method
는 첫번째 argument
에서 자기 자신에 대한 참조를 갖고 있음! (위 예시에서는 potato
가 ruffus
를 의미하므로 같은 주소값을 갖음)class Puppy:
def __init__(self):
self.name = "Ruffus"
self.age = 0.1
self.breed = "Beagle"
ruffus = Puppy()
print(ruffus.name, ruffus.age, ruffus.breed) # Ruffus 0.1 Beagle
class Puppy:
def __init__(self, name, breed):
self.name = name
self.age = 0.1
self.breed = breed
ruffus = Puppy(
name ="Ruffus", breed="Beagle"
)
bibi = Puppy(
name="Bibi", breed="Dalmatian"
)
print(ruffus.name, bibi.name) # Ruffus Bibi
python
은 class
를 위한 정말 많은 밑줄을 활용한 method
가 있음.__str__
은 python의 클래스 내장 메서드
중 하나로 인스턴스를 print 함수로 호출하게 되면 __str__ 의 리턴 값을 실행함
인스턴스(instance)
는 클래스의 객체, 즉 클래스(청사진)를 바탕으로 만들어진 실체를 의미함class Puppy:
def __init__(self, name, breed):
self.name = name
self.age = 0.1
self.breed = breed
def __str__(self):
return "Hello!"
ruffus = Puppy(
name ="Ruffus", breed="Beagle"
)
bibi = Puppy(
name="Bibi", breed="Dalmatian"
)
print(ruffus, bibi) # Hello! Hello!
print(ruffus.breed, bibi.breed) # Beagle, Dalmatian
__method__
와 같이 기본 내장 메서드 외에도 내가 커스텀한 메서드를 사용해서 데이터에 기능성을 입힐 수 있음class Puppy:
def __init__(self, name, breed):
self.name = name
self.age = 0.1
self.breed = breed
def woof_woof(self):
print("woof woof!")
def introduce(self):
self.woof_woof()
print(f"hello my name is {self.name} and i am baby {self.breed}")
self.woof_woof()
ruffus = Puppy(
name ="Ruffus", breed="Beagle"
)
bibi = Puppy(
name="Bibi", breed="Dalmatian"
)
print(ruffus.introduce)
# woof woof!
# hello my name is Ruffus and i am baby Beagle
# woof woof!
상속(inheritance)
은 코드를 저장하고 다시 사용할 수 있게 해줌.Puppy
는 이름, 나이, 품종의 값을 가지고 있는데, 만약 다른 종류의 강아지 (예를 들어 경비견)에 대한 클래스를 만든다면 init 메서드
를 정의하고 puppy 클래스
를 만들 때 했던 작업을 그대로 반복해야 함.class Guard_Dog:
def __init__(self, name):
self.name = name
~~~
상속(inheritance)
의 역할이 필요함. 상속을 통해 위와 같은 과정을 더는 반복하지 않을 수 있음소괄호()를 붙이고 내부에 부모 클래스명을 입력
class Dog:
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
class Guard_Dog(Dog):
class Puppy(Dog):
Guard_Dog
과 Puppy
는 Dog
를 상속하며, 이를 통해 name, age, breed
와 같은 공통 속성을 공유한다는 것을 알 수 있음super
는 Dog
인 부모 클래스를 참조하는 것을 의미함.class Dog:
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
def sleep(self):
print("zzzz")
class Guard_Dog(Dog):
def __init__(self, name, breed):
super().__init__(name, 5, breed)
def grrr(self):
print("grrr")
class Puppy(Dog):
def __init__(self, name, breed):
super().__init__(name, 0.1, breed)
self.aggresive = True
def woof_woof(self):
print("woof woof!")
ruffus = Puppy(
name = "Ruffus",
breed = "Beagle"
)
rufus.woof_woof()
rufus.sleep()
rufus.grrr() # 에러 발생! grrr 메서드는 Guard_Dog 클래스에만 존재함.
class Player:
def __init__(self, name, team):
self.name = name
self.xp = 1500
self.team = team
def introduce(self):
print(f"hello! i`m {self.name} and i play for {self.team}")
class Team:
def __init__(self, team_name):
self.team_name = team_name
self.players = []
def show_players(self):
for player in self.players:
player.introduce()
def add_player(self, name):
new_player = Player(name, self.team_name)
self.players.append(new_player)
team_x = Team("Team X")
team_x.add_player("jung")
blue_team = Team("Team Blue")
team_blue.add_player("kim")
team_blue.show_players() # hello! i`m kim and i play for Team Blue
이 링크를 통해 구매하시면 제가 수익을 받을 수 있어요. 🤗