Class
class Test: # 모든 class 는 object 를 상속받고 있음
def __new__(cls): # class method
print('new call')
return object.__new__(cls) # object class 의 객체생성
def __init__(self): #생성자
print('init call')
self.a = 10
self.b = 20
def __del__(self): #소멸자
print('destory')
@staticmethod
def staticFunc(): # self 가 없으면 static 함수
print('call staticFunc')
obj = Test() # 힙영역에 Test 메모리 할당되고 다음 두 과정이 수행됨
## 1. obj = Test.__new__(Test)
## 2. obj = Test.__init__(obj)
단일객체(singleTone) 만드는법
class Test:
__instance = None
def __new__(cls):
print('new call')
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
obj1 = Test()
obj2 = Test()
print(id(obj1) == id(obj2)) # singleTone 으로써 여러번 생성해도 참조 주소가 같음
상속
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def setName(self, name):
self.name = name
class Student(People):
def __init__(self, name, age, stdNum):
super().__init__(name, age) # 부모 클래스에 접근하기 위한 super 키워드
self.stdNum = stdNum
std = Student('홍길동', 20, 1111)
print(std.name, std.age, std.stdNum)
std.setName('이순신')
print(std.name, std.age, std.stdNum)
출력조건 재정의
class Test:
def __init__(self):
self.a = 10
self.b = 20
def __repr__(self):
return 'a=%d, b=%d'%(self.a, self.b)
obj = Test()
print(obj) # __repr__ 에 의해 '<__main__.Test object at 0x00A6F290>' 형식이 아닌 a=10, b=20 이 출력
'교육 > Pyhotn 180709-180713' 카테고리의 다른 글
4일차 sqlite (0) | 2018.07.12 |
---|---|
4일차 python 확장 - C 언어 (0) | 2018.07.12 |
3일차 library (0) | 2018.07.11 |
2일차 module (0) | 2018.07.10 |
1일차 (0) | 2018.07.09 |