在Python中重置类的首选方法 [英] Preferred way of resetting a class in Python
问题描述
我在Python(3)中有
Foo
类,其中当然包括 __ init __()
方法。此类触发了一些提示并执行其操作。假设我希望能够重置 Foo
,以便我可以重新开始该过程。
I have a class
Foo
in Python (3), which of course includes a __init__()
method. This class fires a couple of prompts and does its thing. Say I want to be able to reset Foo
so I can start the procedure all over again.
那将是什么首选实现?
再次调用 __ init __()
方法
def reset(self):
self.__init__()
或创建新实例?
def reset(self):
Foo()
我不确定是否要创建 Foo $ c的新实例如果多次调用
可能会有副作用。 >。重置
,$ c>会留下任何可能影响性能的内容。另一方面,如果不是所有的属性都在 __ init __()
__ init __()
I am not sure if creating a new instance of Foo
leaves behind anything that might affect performance if reset
is called many times. On the other hand __init__()
might have side-effects if not all attributes are (re)defined in __init__()
.
有没有首选的方法?
推荐答案
两者都是正确的,但语义的实现方式不同。
Both are correct but the semantics are not implemented the same way.
为了能够重置实例,我会这样写(我更喜欢从调用自定义方法 __ init __
相反,因为 __ init __
是一种特殊方法,但这主要是一个品味问题):
To be able to reset an instance, I would write this (I prefere to call a custom method from __init__
than the opposite, because __init__
is a special method, but this is mainly a matter of taste):
class Foo:
def __init__(self):
self.reset()
def reset(self):
# set all members to their initial value
您使用这种方式:
Foo foo # create an instance
...
foo.reset() # reset it
从头开始创建新实例实际上更简单,因为该类无需实现任何实现特殊方法:
Creating a new instance from scratch is in fact simpler because the class has not to implement any special method:
Foo foo # create an instance
...
foo = Foo() # make foo be a brand new Foo
如果旧实例未在其他地方使用,则将对其进行垃圾回收
the old instance will be garbage collected if it is not used anywhere else
两种方法均可用于 normal 类,其中所有初始化均在 __ init __
中完成,但是对于在创建时使用 __ new __
自定义的特殊类(例如不可变类),则需要第二种方法。
Both way can be used for normal classes where all initialization is done in __init__
, but the second way is required for special classes that are customized at creation time with __new__
, for example immutable classes.
但是请注意,此代码:
def reset(self):
Foo()
将不执行您想要的操作:它只会创建一个新实例,并立即删除它,因为它将在方法末尾超出范围。即使 self = Foo()
也会只设置本地引用,该本地引用在方法结束时会超出范围(并且破坏了新实例)。
will not do what you want: it will just create a new instance, and immediately delete it because it will go out of scope at the end of the method. Even self = Foo()
would only set the local reference which would the same go out of scope (and the new instance destroyed) at the end of the methos.
这篇关于在Python中重置类的首选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!