클래스 속성 변경하기
클래스 속성을 정의하고, 인스턴스에서 그 속성에 접근하는 방법을 배웠어요. 그렇다면 인스턴스에서 클래스 속성에 접근한 뒤, 그 속성에 다른 값을 대입하면 어떤 일이 일어날까요?
이전 연습 문제의 Player 클래스가 아래와 같이 미리 정의되어 있어요:
class Player:
MAX_POSITION = 10
def __init__(self, position):
if position <= Player.MAX_POSITION:
self.position = position
else:
self.position = Player.MAX_POSITION
이 연습은 강의의 일부입니다
Python 객체 지향 프로그래밍 입문
연습 안내
Player객체p1과p2를 각각 위치9와5로 생성하세요.p1.MAX_POSITION과p2.MAX_POSITION을 출력하세요.p1.MAX_POSITION에7을 대입하세요.- 다시
p1.MAX_POSITION과p2.MAX_POSITION을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Create Players p1 and p2
p1 = ____
p2 = ____
print("MAX_POSITION of p1 and p2 before assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____
# Assign 7 to p1.MAX_POSITION
____
print("MAX_POSITION of p1 and p2 after assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____