【问题标题】:Why is instantiating python class repeating former actions by other instances before doing new action?为什么在执行新操作之前实例化 python 类会重复其他实例以前的操作?
【发布时间】:2015-08-06 21:51:51
【问题描述】:

我已尝试使用自定义示例尽可能好地表示此问题。

我设置了一个特殊的类,它系统地通过大量的步骤from __init__(self) 向前运行。

一切似乎都很好,除了这个非常奇怪的问题,每次我调用类时,它似乎都会回到过去并在执行新操作之前重复前两个操作。如果我运行它五次,到第五次它会在执行第五个新动作之前重复前 4 个相同的动作,依此类推。

这是一个非常奇怪的问题。这是 django 环境中的 python 交互。希望我的代码示例很好地说明了这个问题:

#file helper_stuff.py
class one_shot_long_process():

    obj=''
    obj2=''

    def init(self, obj, obj2):

        self.obj=obj
        self.obj2=obj2

        self.complex_action()
        self.complex_action_2()

    def complex_action(self):
        '''do lots of things in a row with obj'''

    def complex_action_2(self):
        '''
        Do more stuff, make decisions, loop, etc
        with obj 1, 2
        make entries, do writes

        >>>> WRITE FILES by number (jpegs)
        '''

所以你有一个类的基本示例。它获取 django 模型、处理图像并写入它们。我已经仔细检查过,我认为没有理由以这种方式重复(特别是因为我直接调用类实例,如下所示)

#file interactive_stuff.py    

#!/home/leo/.virtualenvs/illo/bin/python3 -i        
from helper_stuff import one_shot_long_process


>>> one_shot_long_process(obj, obj2)

#WRITES FILE 1.jpg

>>> one_shot_long_process(obj, obj2)

#re-WRITES FILE 1.jpg
#WRITES FILE 2.jpg

>>> one_shot_long_process(obj, obj2)

#re-WRITES FILE 1.jpg
#re-WRITES FILE 2.jpg
#WRITES FILE 3.jpg

这很奇怪——为什么重新调用 one_shot_long_process(obj, obj2) 仍然会导致以前的“实例”重复自己?我该如何解决这个问题?

【问题讨论】:

  • 不管是什么问题,都在你的complex_action_2函数中,你没有给出任何代码。
  • 也许问题是我对调用 one_shot_long_process(obj, obj2) 的类(我从 php 开始)的理解应该每次都重新开始这个过程,对吗?
  • 如果您认为自己的理解有误,请发布实际代码,以便我们得出自己的结论。现在,无论好坏,您都在强加您的理解,因为我们所要做的就是您的描述和您的函数名称。
  • 简单问题:如果我运行一个类实例some_new_class(input),除了它所提供的内容之外,它从不引用外部世界,它应该每次都运行新的,对吗?每次运行some_new_class(input) 时,它都应该是一组全新的数据——不应该引用前一个数据中包含的旧数据——这不是基本的SCOPE 问题吗?我是这样问的,所以我不必发布大量代码。
  • 但是你看不出答案取决于函数在做什么吗?也许它将数据存储在类范围或其他地方。除非你给我们看,否则我们不知道。

标签: python django interactive


【解决方案1】:

如果没有实际代码,我只能猜测,但我会试一试。

您没有“重新”开始,因为one_shot_long_process.objone_shot_long_process.obj2class variables, not instance variables.

让我用一个例子来说明。

class Foo():

    l = []
    def __init__(self, x):
        self.l.append(x)
        print self.l

class Bar():

    def __init__(self, x):
        self.l = []
        self.l.append(x)
        print self.l

Foo(4) # prints [4]
Foo(4) # prints [4, 4]
Bar(4) # prints [4]
Bar(4) # prints [4]

正如其他人所说,如果没有一些实际代码,就无法判断。在您发布的代码中,它没有任何区别。

附带说明,common naming convention for classes 是使用CapWords,即在您的情况下为OneShotLongProcess

【讨论】:

  • 这是我错了和问题所在的代价高昂。我以为每次打电话给 Foo 都是新的!非常感谢,谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-07-01
  • 2015-09-15
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多