[Python]클래스(class)
파이썬의 클래스에 대해 알아보자
# 파이썬 클래스 # 객체지향 프로그래밍 # 네임스페이스 : 객체를 인스턴스화 할 때 저장된 공간 # 클래스 변수 : 직접 접근 가능, 공유 # 인스턴스 변수 : 객체마다 별도 존재 # 예제1 class Dog(object): # 모든 클래스는 object를 상속 # 클래스 속성(클래스 변수) species = 'firstdog' # 초기화/인스턴스 속성(변수) def __init__(self, name, age): self.name = name self.age = age # 클래스 정보 print(Dog) # 인스턴스화 a = Dog('바둑이', 3) b = Dog('점박이', 2) # 비교 print(a == b, id(a)) # 네임스페이스 print('dog1', a.__dict__) print('dog2', b.__dict__) # 인스턴스 속성 확인 print('{} is {} and {} is {}'.format(a.name, a.age, b.name, b.age)) if a.species == 'firstdog': print('{0} is a {1}'.format(a.name, a.age)) print(Dog.species) print(a.species) print(b.species) print() # 예제2 # self의 이해 class SelfTest: def func1(): # 클래스 메서드 print('Func1 called') def func2(self): # 인스턴스 메서드 print(id(self)) # 인스턴스화 된 변수가 넘어간다. f = SelfTest()에서 f 가 넘어온다. print('Func2 called') f = SelfTest(); print(dir(f)) print(id(f)) # f.func1() 이렇게 사용하면 예외가 발생한다. f.func2() SelfTest.func1() # 인스턴스가 아닌 클래스를 통해서 접근가능하다. # SelfTest.func2() # 인스턴스화된 변수가 존재하지 않아 예외가 발생한다. SelfTest.func2(f) # 클래스가 아닌 인스턴스화된 변수를 넘겨야 접근가능하다. 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('jigi') user2 = Warehouse('im') print(Warehouse.stock_num) print(user1.name) print(user2.name) print(user2.__dict__) print(user2.__dict__) print('before : ', Warehouse.__dict__) print(user1.stock_num) del user1 print('after : ', Warehouse.__dict__) print() # 예제4 class Dog: # 모든 클래스는 object를 상속 species = 'firstdog' def __init__(self, name, age): self.name = name self.age = age def info(self): return f'{self.name} is {self.age} years old' def speak(self, sound): return f'{self.name} says {sound}!' # 인스턴스 생성 C = Dog('멍멍이', 4) D = Dog('꼬끼오', 3) print(C.info()) print(C.speak('멍멍')) print(D.info()) print(D.speak('꼬꼬'))
결과:
<class '__main__.Dog'> False 2019585212368 dog1 {'name': '바둑이', 'age': 3} dog2 {'name': '점박이', 'age': 2} 바둑이 is 3 and 점박이 is 2 바둑이 is a 3 firstdog firstdog firstdog ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'func1', 'func2'] 2019585211552 2019585211552 Func2 called Func1 called 2019585211552 Func2 called 2 jigi im {'name': 'im'} {'name': 'im'} before : {'__module__': '__main__', 'stock_num': 2, '__init__': <function Warehouse.__init__ at 0x000001D638A7F7F0>, '__del__': <function Warehouse.__del__ at 0x000001D638A7F130>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None} 2 after : {'__module__': '__main__', 'stock_num': 1, '__init__': <function Warehouse.__init__ at 0x000001D638A7F7F0>, '__del__': <function Warehouse.__del__ at 0x000001D638A7F130>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None} 멍멍이 is 4 years old 멍멍이 says 멍멍! 꼬끼오 is 3 years old 꼬끼오 says 꼬꼬!
최신 댓글