Player 클래스를 정의하고 객체를 생성
# 플레이어 클래스
class Player:
# 생성자
# 클래스의 인스턴스가 생성될때 호출됨
def __init__(self):
# 플레이어 멤버 변수 hp를 10으로 초기화
self.hp = 10
# 파괴자
def __del__(self):
# 별다른 처리가 없는경우 pass 키워드를 설정해둔다(공백은 안됨)
pass
# 정보를 출력
def PrintInfo(self):
print("hp - {hp}".format(hp=self.hp))
# 플레이어 클래스 인스턴스
myPlayer = Player()
# 멤버 함수를 호출
myPlayer.PrintInfo()
def __init__(self):
클래스 객체가 생성될때 자동으로 호출되는 함수
멤버 변수는 여기서 선언하고 초기화 해준다
def __del__(self):
클래스 객체가 제거될때 자동으로 호출되는 함수
파일같은 관리되는 객체가 있는경우 파일 닫기와 같은 정리 로직을 넣어준다
def PrintInfo(self):
인스턴스 함수로 객체를 생성하고 호출 가능
__dict__
클래스 객체에 변수선언시 자동으로 등록되어 맵형태로 관리
기본 클래스 메소드
__new__ | 클래스 객체가 생성될때 호출 |
__init__ | 클래스 객체가 초기화될때 자동으로 호출되는 함수 |
__del__ | 클래스 객체가 파괴될때 자동으로 호출되는 함수 |
__setattr__(self, name, value) | 클래스 객체에 변수를 설정할 때 호출 |
__eq__(self, other) | == |
__ne__(self,other) | != |
__lt__(self,other) | < |
__le__(self,other) | <= |
__gt__(self,other) | > |
__ge__(self,other) | >= |
__setattr__ 의 사용
class TestClass:
def __setattr__(self, name, value):
print("{NAME}:{VALUE}".format(NAME=name, VALUE=value))
super.__setattr__(self, name, value)
# 객체 생성
t = TestClass()
# 값을 설정. 여기서 "a:4" 가 출력됨
t.a = 4
'Python > 기본' 카테고리의 다른 글
[Python] 반복문 for (1) | 2024.09.08 |
---|---|
[Python] list (0) | 2024.09.08 |
[Python] 함수 정의 및 호출 (0) | 2024.09.07 |
[Python] 조건문 if, match-case (1) | 2024.09.01 |
[Python] 변수 (0) | 2024.08.31 |