且构网

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

更改实例方法中的类实例

更新时间:2023-12-02 19:54:28

self = Test(3)是重新绑定本地名称 self ,没有外部可观察的效果。

self = Test(3) is re-binding the local name self, with no externally observable effects.

分配 self .__ dict __ (除非你在谈论具有 __ slots __ 或来自具有非平凡元类的类的实例)通常是正确的,因此 self .__ init __(3 )重新初始化实例。但我更喜欢有一个特定的方法 self.restart(3)其中知道它在一个已经初始化的实例上调用,需要满足这种特殊和不寻常的情况。

Assigning self.__dict__ (unless you're talking about instances with __slots__ or from classes with non-trivial metaclasses) is usually OK, and so is self.__init__(3) to re-initialize the instance. However I'd prefer to have a specific method self.restart(3) which knows it's being called on an already-initialized instance and does whatever's needed to cater for that specific and unusual case.