У меня есть класс в Python, который немного больше, чем примитивные значения, такие как int
или float
, см. Ниже
class Entry:
def __init__(self, value, timestamp):
self.value = value
self.timestamp = timestamp
def __str__(self):
return"[v= {}, ts= {}]".format(self.value, self.timestamp)
def __hash__(self):
return hash(self.timestamp)
def __eq__(self, other):
return self.timestamp == other.timestamp
def __le__(self, other):
return self.timestamp <= other.timestamp
def __lt__(self, other):
return self.timestamp < other.timestamp
def __ge__(self, other):
return self.timestamp >= other.timestamp
def __gt__(self, other):
return self.timestamp > other.timestamp
def __copy__(self):
new_entry = Entry(deepcopy(self.value), self.timestamp)
print("hi")
return new_entry
e1 = Entry("some name", 10)
e2 = e1
e2.timestamp = 20
print(e1)
Я хочу, чтобы он вел себя так же, как и примитивные типы,Поэтому, когда происходит присвоение, как указано выше, значение копируется глубоко, поэтому мне не нужно думать о том, чтобы делать это вручную везде, где я делаю присвоение, подобное этому.
Как видите, я попытался переопределить__copy__
метод.К сожалению, этот метод здесь не вызывается.Есть ли другой способ переопределить?Я уверен, что это может быть достигнуто в C ++.Можно ли это сделать и в Python?