반응형

/************************************************************************************************
-- Title : [PY2.7.11] 클래스 변수, 객체 변수, 클래스 메소드
-- Reference : itsdong.com
-- Key word : 클래스 변수, 객체 변수, 클래스 메소드
************************************************************************************************/

# -*- coding: utf-8 -*-

# -----------------------------------------------
# -- __init__ Method
# -- 객체가 생성될 때, 여러 초기화 작업이 사용
# -----------------------------------------------
class Person:
def __init__(self, name): # 메소드
self.name = name # 필드

def say(self):
print('My name is ' + self.name)

p1 = Person('Hayden.Choi')
p1.say()

print('-' * 100)

# -----------------------------------------------
# -- 클래스 변수 vs. 개체 변수
# -----------------------------------------------
class Man:
# 클래스 변수
cnt = 0

def __init__(self, name): # 생성자, 초기자
self.name = name
print('Initiated...{}'.format(self.name))

Man.cnt += 1 # 클래스 변수에 접근 : 클래스.클래스변수

def die(self):
print('{} was killed.'.format(self.name))

Man.cnt -= 1

if Man.cnt == 0:
print('The man who was killed {} is a last man'.format(self.name))
else:
print('{:d} person(s) is/are still alive.'.format(Man.cnt))

def say(self):
print('Hell, my name is {}.'.format(self.name))

@classmethod #장식자(decorator) : how_many = classmethod(how_many)
def how_many(how):
print('There is/are {:d} person(s) left.'.format(Man.cnt))

# -- 게이머 추가
gameactor1 = Man('Jane')
gameactor1.say()

# -- 명수 확인
Man.how_many() # gameactor1.how_many()와 동일

# -- 게이머 추가
gameactor2 = Man('Paul')
gameactor2.say()

# -- 명수 확인
gameactor3 = Man('Tom')
gameactor1.how_many()

# -- 게이머 삭제
gameactor1.die() # Jane을 죽이고 카운팅
gameactor1.how_many() # Man.cnt가 계속 공유됨





반응형

+ Recent posts