카테고리 없음
[python] Python copy.deepcopy () 함수가 제대로 작동하지 않음 [중복]
행복을전해요
2021. 2. 23. 18:08
The problem is that you are actually copying the class definition and not an instance of the class.
Another problem of the code is that the attributes age
and score
are part of the class and will be shared between all instances of that class. This is probably not what you intended.
What you probably want to do is:
import copy
class Player:
def __init__(self, age, score):
self.age = age
self.score = score
player1 = Player(23, 1)
player2 = Player(14, 2)
player3 = copy.deepcopy(player1)
player1.age += 1
print "player1.age", player1.age
print "player3.age", player3.age
This gives you what you expect:
player1.age 24
player3.age 23
-------------------From the documentation (emphasis mine):
이 버전은 모듈, 클래스 , 함수, 메소드, 스택 추적, 스택 프레임, 파일, 소켓, 창, 배열 또는 유사한 유형과 같은 유형을 복사하지 않습니다 .
클래스를 복사하려고합니다.
>>> player3 = copy.deepcopy(player1)
>>> player1 is player3
True
그러나
>>> p1 = player1()
>>> p2 = player2()
>>> p3 = copy.deepcopy(p1)
>>> p1 is p3
False
-------------------이것은 설계된대로 작동합니다.
샘플 코드에서 개체 인스턴스가 아닌 클래스 정의를 복사합니다. 에서 copy
모듈 매뉴얼 페이지 :
It does “copy” functions and classes (shallow and deeply), by returning the original object
unchanged
그 후:
player3 = copy.deepcopy(player1)
와 같다:
player3 = player1
그러나 클래스의 인스턴스를 복사하면 예상되는 결과를 얻을 수 있습니다.
player3 = copy.deepcopy(player1())
출처
https://stackoverflow.com/questions/22080051