当引用成为引用对象时,如何使python对象自身或属性不分配给引用对象? [英] How to make a python objects self or attribute not get assigned to the referencer object when it is references?

查看:95
本文介绍了当引用成为引用对象时,如何使python对象自身或属性不分配给引用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望当一个对象被另一个对象,引用者的自身对象或其属性之一在引用者对象处不同时

I want when a object is referenced by another, the refernecer's self object or one of it's attributes to be different at the referencer object

这就是我想做的:

class MyClass:
    .
    .
    .
    .

a = MyClass()
b = a
print(b is a) #must print false
print(b == a) #must print true

#or
a = MyClass()
b = a
print(b.attr is a.attr) #must print false
print(b.attr == a.attr) #must print true

我如何实现这一目标,通常是在进行 a = b b 是对 a 的引用,值得赞赏的是,我希望 b a 的副本/深拷贝,与属性

How can I achieve this, normally the when an assignment is made like a = b, b is a reference to a, any help would be appreciated, I want b to be a copy/deepcopy of a, same for the attribute

从现在开始感谢将要回答问题的人

Thanks from now for the people who will answer the question

注意:我正在使用CPython(Python的官方实现)版本Python 3.8

Note: I’m using CPython (the official implemention of Python) version Python 3.8

我愿意使用黑魔法

推荐答案

您不应尝试对重载进行任何操作因为那不是很pythonic。使用 deepcopy 函数或将其复制为构造函数。然后覆盖 __ eq __ 函数,以使两个变量测试相等。

You shouldn't try to do anything with overloading assignment as that's not very pythonic. Either use the deepcopy function or make a copy "constructor". Then override the __eq__ function so that the two variables test equal.

这篇关于当引用成为引用对象时,如何使python对象自身或属性不分配给引用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆