且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在方法中用另一个相同类型的对象替换 self 对象是否安全?

更新时间:2023-01-08 13:34:07

替换 '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.