
Python 클래스 알아보기
# chapter06-1
# 파이썬 클래스
# OOP(객체 지향 프로그래밍), Self, 인스턴스 메소드, 인스턴스 변수
# 클래스 and 인스턴스 차이 이해
# 네임스페이스 : 객체를 인스턴스화 할 때 저장된 공간
# 클래스 변수 : 직접 접근 가능
# 인스턴스 변수 : 객체마다 별도 존재
# 예제 1
class Dog(object): # (object)생략해도 됨
# 클래스 속성
species = 'first_dog'
# 초기화/인스턴스 속성
def __init__(self, name, age):
self.name = name
self.age = age
# 클래스 정보 출력
print(Dog) # <class '__main__.Dog'>
print()
# 인스턴스화
a = Dog("Bora", 13)
b = Dog("Star", 11)
c = Dog("Kong", 5)
d = Dog("Bora", 13)
# 비교
print(a == b, id(a), id(b)) # False (각 인스턴스는 다른 메모리 주소)
print()
# 네임스페이스
print('dog1', a.__dict__) # dog1 {'name': 'Bora', 'age': 13}
print('dog2', b.__dict__) # dog2 {'name': 'Star', 'age': 11}
print()
# 인스턴스 속성 확인
print('{} is {} and {} is {}.'.format(a.name, a.age, b.name, b.age))
# Bora is 13 and Star is 11.
print()
if a.species == 'first_dog':
print('{0} is a {1}'. format(a.name, a.species)) # Bora is a first_dog
print(Dog.species) # first_dog
print(a.species) # first_dog
print(b.species) # first_dog
print(c.species) # first_dog
print(d.species) # first_dog
print()
# 예제 2
# self의 이해 : 나만의 인스턴스의 속성
class SelfTest:
def func1():
print('Func1 called')
def func2(self):
print('Func2 called')
f = SelfTest()
print(dir(f)) # f 객체의 모든 속성과 메소드 리스트 출력
print(id(f)) # f 객체의 고유 id 값 출력
# f.func1() : 에러발생 / 예외
f.func2() # Func2 called
SelfTest.func1() # Func1 called
# SelfTest.func2() : 에러발생 / 예외
SelfTest.func2(f) # Func2 called
print()
# 예제 3
# 클래스(모두 공유) 변수, 인스턴스(나만의) 변수
class warehouse:
# 클래스 변수
stock_num = 0
def __init__(self, name):
self.name = name
warehouse.stock_num += 1
def __del__(self):
warehouse.stock_num -= 1
user1 = warehouse('Lee')
user2 = warehouse('Cho')
print(warehouse.stock_num) # 2
print(user1.name) # Lee
print(user2.name) # Cho
print(user1.__dict__) # {'name': 'Lee'}
print(user2.__dict__) # {'name': 'Cho'}
print(warehouse.__dict__) # 클래스 변수 포함된 딕셔너리 출력
print('Before : ', warehouse.__dict__)
print(user1.stock_num) # 2
del user1
print('After : ', warehouse.__dict__)
print()
# 예제 4
class Dog2(object):
# 클래스 속성
species = 'first_dog'
# 초기화/인스턴스 속성
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
return '{} is {} years old.'.format(self.name, self.age)
def speak(self, sound):
return '{} barks {}!'.format(self.name, sound)
# 인스턴스 생성
c = Dog2("Kong", 5)
d = Dog2("Cloud", 13)
# 메소드 호출
print('{} is {} years old.'.format(c.name, c.age)) # Kong is 5 years old.
print(c.info()) # Kong is 5 years old.
print(c.speak('wal wal')) # Kong barks wal wal!
print(d.speak('mung mung')) # Cloud barks mung mung!
print()