将对象重置为初始状态

2024-09-29 17:15:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个关于重置对象的适当方法的指针(当前的计划代码)。下面是我目前的想法。唯一的问题是,在其他方法中定义的许多其他属性在我调用init时不会被删除。对于我构建对象的方式来说,这不是问题(当运行模拟方法时,init中未定义的所有属性都会重新计算)。但是,我觉得它不是干净的——我更喜欢完全重置到初始化状态,并且不在init之外定义任何属性

class foo:

        def __init__(self, formaat):
                self.format == formaat
                # process format below:
                if formaat == one:
                        self.one = 1
                if formaat == two:
                        self.two = 2
                # ... other parameter imports below - dependent on the value of self.one/self.two

        def reset(self, formaat):
                self.__init__(formaat)

        def simulate(self):
                self.reset(self.format)
                print("doing stuff")

我尝试过的一件事是有一种复制自己的方法。尽管我认为这样做与在运行脚本中复制对象并重新分配对象之间没有任何区别

class foo:

    def __init__(self, formaat):
                self.format = formaat
                # process format below:
                if formaat == one:
                        self.one = 1
                if formaat == two:
                        self.two = 2
                # ... other parameter imports below

    def copymyself(self):
        self.copy = copy.deepcopy(foo(self.format)) 

    def simulate(self):
        print("doing stuff")

理想情况下,我希望模拟方法在每次启动时都重置自己。在上面的示例代码中,我必须执行以下运行脚本

a = foo()
# loop the code below
a.copymyself()
a.simulate()
a = a.copy

我更喜欢使用一行-a.simulate(),就像使用reset方法时一样


Tags: 对象方法selfformatif属性fooinit

热门问题