파이썬에서 생성자를 복사 하시겠습니까?
파이썬에 복사 생성자가 있습니까? 그렇지 않다면 비슷한 것을 달성하기 위해 무엇을 할 것입니까?
상황은 내가 라이브러리를 사용하고 있고 추가 기능으로 클래스 중 하나를 확장했으며 라이브러리에서 가져온 객체를 내 클래스의 인스턴스로 변환 할 수 있기를 원합니다.
복사 모듈 을 원한다고 생각합니다
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
pickle 을 제어하는 것과 거의 같은 방식으로 복사를 제어 할 수 있습니다 .
파이썬에서 복사 생성자는 기본 인수를 사용하여 정의 할 수 있습니다. 일반 생성자가 함수를 실행 non_copy_constructor(self)
하고 복사 생성자가 실행 되기를 원한다고 가정 해 보겠습니다 copy_constructor(self, orig)
. 그런 다음 다음을 수행 할 수 있습니다.
class Foo:
def __init__(self, orig=None):
if orig is None:
self.non_copy_constructor()
else:
self.copy_constructor(orig)
def non_copy_constructor(self):
# do the non-copy constructor stuff
def copy_constructor(self, orig):
# do the copy constructor
a=Foo() # this will call the non-copy constructor
b=Foo(a) # this will call the copy constructor
복사 생성자의 일반적인 구현에 대한 간단한 예 :
import copy
class Foo:
def __init__(self, data):
self._data = data
@classmethod
def from_foo(cls, class_instance):
data = copy.deepcopy(class_instance._data) # if deepcopy is necessary
return cls(data)
귀하의 상황에 따라 라이브러리 클래스의 인스턴스를 인수로 취하고 적용 가능한 모든 속성이 복사 된 클래스의 인스턴스를 반환하는 클래스 메서드 (또는 정적 메서드 또는 별도의 함수일 수 있음)를 작성하는 것이 좋습니다.
@Godsmith의 사고 방식을 기반으로 생성자 내의 모든 속성에 대한 데이터 복사를 수행해야하는 @Zitrax의 요구 사항을 해결합니다.
class ConfusionMatrix(pd.DataFrame):
def __init__(self, df, *args, **kwargs):
try:
# Check if `df` looks like a `ConfusionMatrix`
# Could check `isinstance(df, ConfusionMatrix)`
# But might miss some "ConfusionMatrix-elligible" `DataFrame`s
assert((df.columns == df.index).all())
assert(df.values.dtype == int)
self.construct_copy(df, *args, **kwargs)
return
except (AssertionError, AttributeError, ValueError):
pass
# df is just data, so continue with normal constructor here ...
def construct_copy(self, other, *args, **kwargs):
# construct a parent DataFrame instance
parent_type = super(ConfusionMatrix, self)
parent_type.__init__(other)
for k, v in other.__dict__.iteritems():
if hasattr(parent_type, k) and hasattr(self, k) and getattr(parent_type, k) == getattr(self, k):
continue
setattr(self, k, deepcopy(v))
이 ConfusionMatrix
클래스는 a를 상속 pandas.DataFrame
하고 other
행렬 데이터를 복사 할 수 없는 경우 다시 계산해야하는 많은 다른 속성과 메서드를 추가합니다 . 해결책을 찾는 것이이 질문을 찾은 방법입니다.
I have a similar situation differing in that the new class only needs to copy attributes. Thus using @Dunham's idea and adding some specificity to @meisterluk's suggestion, @meisterluk's "copy_constructor" method could be:
from copy import deepcopy
class Foo(object):
def __init__(self, myOne=1, other=None):
self.two = 2
if other <> None:
assert isinstance(other, Foo), "can only copy instances of Foo"
self.__dict__ = deepcopy(other.__dict__)
self.one = myOne
def __repr__(self):
out = ''
for k,v in self.__dict__.items():
out += '{:>4s}: {}, {}\n'.format(k,v.__class__,v)
return out
def bar(self):
pass
foo1 = Foo()
foo2 = Foo('one', foo1)
print '\nfoo1\n',foo1
print '\nfoo2\n',foo2
The output:
foo1
two: <type 'int'>, 2
one: <type 'int'>, 1
foo2
two: <type 'int'>, 2
one: <type 'str'>, one
참고URL : https://stackoverflow.com/questions/1241148/copy-constructor-in-python
'Program Tip' 카테고리의 다른 글
C에서 복잡한 프로젝트를 어떻게 구성해야합니까? (0) | 2020.10.12 |
---|---|
자바 스크립트에서 모든 시간 초과 / 간격을 보십니까? (0) | 2020.10.12 |
Python에서 open과 codecs.open의 차이점 (0) | 2020.10.12 |
클래스 확장 대 클래스 범주 (0) | 2020.10.12 |
GitHub 위키 디렉토리 (0) | 2020.10.12 |