새소식

데이터분석/둘째주

파이썬 Python : 얕은 복사, 깊은 복사

  • -
728x90

 

 

객체와 메모리

변수는 객체의 메모리 주소를 저장하고 이를 이용해서 객체를 참조한다.

레퍼런스 변수 : 메모리 주소를 가지고 객체를 참조하는 변수

class Car:
	def __init__(self, color):
		self.color = color
        
car1 = Car('red')
Stack Memory (스택 메모리)   Heap Memory (힙 메모리)
    객체(Object) 생성  [ Car ]
변수 [ car1 ] ── 참조 ──▶ 객체(Object)   [ Car ]
__init__ 함수의 변수 [ color ] ── 참조 ──▶ [ 'red' ]
__init__ 함수의 self (객체를 가리키는 참조자 역할) ── 참조 ──▶ 객체(Object)
    객체(Object)의 변수 [ color ]
   │ 참조
  ▼
[ 'red' ]

 

car2 = Car('blue')
car3 = car2   #car2에 담긴 메모리 주소가 car3에 넘어감
Stack Memory (스택 메모리)     Heap Memory (힙 메모리)
    객체(Object) 생성  [ Car ]
변수 [ car2 ] ── 참조 ──▶ 객체(Object)   [ Car ]
__init__ 함수의 변수 [ color ] ── 참조 ──▶ [ 'blue' ]
__init__ 함수의 self (객체를 가리키는 참조자 역할) ── 참조 ──▶ 객체(Object)
    객체(Object)의 변수 [ color ]
   │ 참조
  ▼
[ ' blue ' ]
변수 [ car3 ] ── 참조 ──▶ 변수 [ car2 ]가 참조하는 객체(Object)   [ Car ]

 

 

728x90

얕은 복사 : =

객체 주소를 복사하는 것으로 객체 자체가 복소되지 않는다.

변수가 참조하는 메모리 주소만 복사되는 것

 

 

 

깊은 복사 : 변수명.copy( ) 또는 copy 모듈의 copy( )함수 사용

객체 자체를 복사하는 것으로 또 하나의 객체가 만들어진다.

변수가 참조하는 메모리 주소에 있는 실제 객체를 복사해서 새로운 메모리 주소를 넘겨주는 것

 

 

class Robot:
	def __init__(self, color, height, weight):
		self.color = color
	    self.height = height
	    self.weight = weight

	def printRobotInfo(self):
		print(f'color: {self.color = color}')
	    print(f'height: {self.height = height}')
	    print(f'weight: {self.weight = weight}')
    
rb1 = Robot('red', 200, 80)
rb2 = Robot('blue', 300, 120)
rb3 = rb1 #얕은 복사, rb1이 가지고 있는 객체 주소의 값이 rb3에 복사됨
rb4 = rb2.copy() # 깊은 복사

print('rb1 --')
rb1.printRobotInfo()
print('rb2 --')
rb2.printRobotInfo()
print('rb3 --')
rb3.printRobotInfo()
print('rb4 --')
rb4.printRobotInfo()


rb1.color = 'gray'
rb1.height = 250
rb1.weight = 100
rb2.color = 'black'
rb1.height = 600
rb1.weight = 50

print('rb1 --')
rb1.printRobotInfo()
print('rb2 --')
rb2.printRobotInfo()
print('rb3 --')
rb3.printRobotInfo()
print('rb4 --')
rb4.printRobotInfo()

 

반응형
class TemCls:
	def __init__(self, n, s):
    	self.number = n
        self.str = s

	def printClsInfo(self):
    	print(f'self.number : {self.number}')
        print(f'self.str : {self.str}')

tc1 = TemCls(10, 'hellp')

#얕은 복사
tc2 = tc1

print('tc1 --')
tc1.printClsInfo()
print('tc2 --')
tc2.printClsInfo()
print()

tc2.number = 3.14
tc2.str = 'Bye'

print('tc1 --')
tc1.printClsInfo()
print('tc2 --')
tc2.printClsInfo()


#깊은 복사
import copy

tc1 = TemCls(10, 'hellp')
tc3 = copy.copy(tc1)

print('tc1 --')
tc1.printClsInfo()
print('tc3 --')
tc3.printClsInfo()
print()

tc3.number = 9.9
tc3.str = 'Bye'


print('tc1 --')
tc1.printClsInfo()
print('tc3 --')
tc3.printClsInfo()

 

 

scores = [9, 43, 23, 1, 56]
scoresCopy = []

for s in scores:
	scoresCopy.append(s) #깊은 복사
    
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

 

scores = [9, 43, 23, 1, 56]
scoresCopy = []

scoresCopy.extend(scores) #깊은 복사
    
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

 

 

scores = [9, 43, 23, 1, 56]
scoresCopy = []

scoresCopy = scores.copy() #깊은 복사
    
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

 

 

scores = [9, 43, 23, 1, 56]
scoresCopy = []

scoresCopy = scores[:] #깊은 복사
    
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

 

 

 

[실습] 국어, 영어, 수학 점수를 입력받아 리스트에 저장하고 원본을 유지한 상태로, 복사본을 만들어 입력받은 값의 평균과 과목별 점수를 10% 올렸을 경우의 평균을 출력해 보자.

print('과목별 점수 입력')
scoreInfo = [int(input('국어 점수: ')),
			int(input('영어 점수: ')),
			int(input('수학 점수: '))]

print(scoreInfo)

copyScore = scoreInfo.copy()

for idx, score in enumerate(copyScore):
	result = score * 1.1
    copyScore[idx] = 100 if result > 100 else result
    
print(f'이전 평균 : {sum(scoreInfo) / len(scoreInfo)}')
print(f'이후 평균 : {sum(copyScore) / len(copyScore)}')

 

 

 

[실습] 선수의 원본 점수를 이용해서 평균을 출력하고, 최고값과 최저값을 제외한 평균을 출력하는 프로그램을 만들어보자.

p1OriScore = [8.5, 9.9, 7.5, 8.8, 9.5, 9.2, 9.1, 7.9]
p1CopScore = plOriScore.copy()

p1OriScore.sort()

p1CopScore.sort()
p1CopScore.pop(0)
p1CopScore.pop()

print(f'p1OriScore: {p1OriScore}')
print(f'p1CopScore: {p1CopScore}')
print()

oriTotal = round(sum(p1OriScore), 2)
oriAverage = round(oriTotal / len(p1OriScore), 2)
print(f'Original Total: {oriTotal}')
print(f'Original Average: {oriAverage}')
print()

copTotal = round(sum(p1CopScore), 2)
copAverage = round(copTotal / len(p1CopScore), 2)
print(f'Copy Total: {copTotal}')
print(f'Copy Average: {copAverage}')
print()

print(f'Original Average - Copy Average: {oriAverage - copAverage}')

 

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.