반응형
클래스의 개념
namespace : 객체마다 별도 존재
class 변수 : 직접 접근 가능, 공유
인스턴스 변수 : 객체마다 별도 존재
class Dog: # object 상속
# 클래스 속성
species = 'firstdog'
# 초기화/인스턴스 속성
def __init__(self, name, age):
self.name = name
self.age = age
# 클래스 정보
print(Dog)
>>> <class '__main__.Dog'>
# 인스턴스화
a = Dog("mikky", 2)
b = Dog("baby", 3)
# 비교
print(a == b, id(a), id(b))
>>> False 4560946848 4560946704
# 네임스페이스
print('dog1', a.__dict__)
print('dog2', b.__dict__)
>>> dog1 {'name': 'mikky', 'age': 2}
>>> dog2 {'name': 'baby', 'age': 3}
# 인스턴스 속성 확인
print('{} is {} and {} is {}'.format(a.name, a.age, b.name, b.age))
>>> mikky is 2 and baby is 3
if a.species == 'firstdog':
print('{0} is a {1}'.format(a.name, a.species))
>>> mikky is a firstdog
print(Dog.species)
print(a.species)
print(b.species)
>>> firstdog
>>> firstdog
>>> firstdog
Self의 이해
self가 있으면 인스턴스 매소드 -> f.func2() or SelfTest.func2(f)로 호출
self가 없다면 클래스 매소드 -> SelfTest.func1()로 호출
class SelfTest:
def func1():
print('Func1 called')
def func2(self):
print(id(self))
print('Func2 called')
f = SelfTest()
print(id(f))
>>> 4367323440
# f.func1() # 예외
f.func2()
SelfTest.func1()
# SelfTest.func2() # 예외
SelfTest.func2(f)
클래스 변수 & 인스턴스 변수
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
# Warehouse.stock_num = 0.0094
print(user1.name)
print(user2.name)
print(user1.__dict__)
print(user2.__dict__)
print('before', Warehouse.__dict__)
print('>>>', user1.stock_num)
>>> Lee
>>> Cho
>>> {'name': 'Lee'}
>>> {'name': 'Cho'}
>>> before {'__module__': '__main__', 'stock_num': 2, '__init__': <function Warehouse.__init__ at 0x1080d9790>, '__del__': <function Warehouse.__del__ at 0x1080d98b0>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}
>>> 2
del user1
print('after', Warehouse.__dict__)
>>> after {'__module__': '__main__', 'stock_num': 1, '__init__': <function Warehouse.__init__ at 0x1080d9790>, '__del__': <function Warehouse.__del__ at 0x1080d98b0>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}
class Dog: # object 상속
# 클래스 속성
species = 'firstdog'
# 초기화/인스턴스 속성
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 "{} says {}!".format(self.name, sound)
# 인스턴스 생성
c = Dog('july', 4)
d = Dog('Marry', 10)
# 메소드 호출
print(c.info())
print(d.info())
>>> july is 4 years old
>>> Marry is 10 years old
# 메소드 호출
print(c.speak('Wal Wal'))
print(d.speak('Mung Mung'))
>>> july says Wal Wal!
>>> Marry says Mung Mung!
해당 글은 인프런의 [프로그래밍 시작하기 : 파이썬 입문-Inflearn Original ] 강의를 듣고 정리한 개인적인 학습 노트 입니다.
반응형