在方法中用另一个相同类型的对象替换 self 对象是否安全? [英] Is it safe to replace a self object by another object of the same type in a method?

查看:44
本文介绍了在方法中用另一个相同类型的对象替换 self 对象是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用这样的方法中的另一个实例替换一个对象实例:

I would like to replace an object instance by another instance inside a method like this:

class A:
    def method1(self):
        self = func(self)

从数据库中检索对象.

推荐答案

替换 'self' 变量不太可能完成你想要做的任何事情,这不能通过存储 func 的结果来完成(self) 在不同的变量中.self"实际上是一个仅在方法调用期间定义的局部变量,用于传入正在操作的类的实例.替换 self 实际上不会替换对其他对象持有的类的原始实例的引用,也不会创建对分配给它的新实例的持久引用.

It is unlikely that replacing the 'self' variable will accomplish whatever you're trying to do, that couldn't just be accomplished by storing the result of func(self) in a different variable. 'self' is effectively a local variable only defined for the duration of the method call, used to pass in the instance of the class which is being operated upon. Replacing self will not actually replace references to the original instance of the class held by other objects, nor will it create a lasting reference to the new instance which was assigned to it.

这篇关于在方法中用另一个相同类型的对象替换 self 对象是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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