
class Car:
def __init__(self, col, len): # 생성자, Car()와 대응되는 메써드
self.color = col
self.length = len
def doStop(self):
print('Stop!!')
def doStart(self):
print('Start!!')
def printCarInfo(self):
print(f'self.color: {self.color}')
print(f'self.length: {self.length}')
car1 = Car('red', 200)
car1.doStop() # Stop!!
car1.printCarInfo() # self.color: red \n self.length: 200
car1.color = 'white'
car1.printCarInfo() # self.color: white \n self.length: 200
import copy
class Car:
def __init__(self, color):
self.color = color
def printCarInfo(self):
print(f'{self.color}')
car1 = Car('red')
car2 = car1 # 얕은 복사
car3 = copy.copy(car1) # 깊은 복사
car1.printCarInfo() # red
car2.printCarInfo() # red
car3.printCarInfo() # red
car1.color = 'blue'
car1.printCarInfo() # blue
car2.printCarInfo() # blue
car3.printCarInfo() # red
강의에서는 위 방법이 깊은 복사라고 소개되었고, 실제로 각각 복사했을 때 id값이 다른 것을 확인할 수 있었다.
하지만 찾아보니 각 방법에는 그 안의 요소에 대한 매모리값은 고려되지 않아, 리스트 안에 리스트가 있는 경우 등 mutable(가변형) 자료형 안에 mutable 자료가 들어있는 경우 내부 자료의 주소값이 동일하다.a = [[1,2], [3,4]] b = a[:] print(id(a)) # 4395624328 print(id(b)) # 4396179592 print(id(a[0])) # 4396116040 print(id(b[0])) # 4396116040 print(a) # [[1,2], [3,4]] print(b) # [[1,2], [3,4]] a[0][0] = 9 print(a) # [[9,2], [3,4]] print(b) # [[9,2], [3,4]]
copy.deepcopy() 메서드를 활용해 깊은 복사를 할 수 있다.
class Car:
def drive(self):
print('GO')
class Carr(Car):
def back(self):
print('BACK')
car1 = Carr()
car1.drive() # GO
class P_Class:
def __init__(self, pNum1, pNum2):
print('[P_Class] __init__() called!')
self.pNum1 = pNum1
self.pNum2 = pNum2
class C_Class(P_Class):
def __init__(self, cNum1, cNum2):
print('[C_Class] __init__() called!')
# P_Class.__init__(self, cNum1, cNum2)
super().__init__(cNum1, cNum2)
self.cNum1 = cNum1
self.cNum2 = cNum2
cls = C_Class(20, 30) # [C_Class] __init__() called!, [P_Class] __init__() called!'