【问题标题】:Interfering objects (or something less sinister?)干扰物体(或不那么险恶的东西?)
【发布时间】:2012-09-06 21:37:27
【问题描述】:

我创建了一个 word 对象,它只包含两个方法,并且只接受两个参数。尽管看起来很简单,但它的行为方式超出了我的理解:如果我创建同一个对象的两个实例,使用相同的第一个参数(在本例中为“伪装”),第二个实例会以某种方式干扰第一个实例。打印实例表明它们确实是分开的,那么为什么会以这种方式交互呢?

# Example tested with Python 2.7.3

from collections import namedtuple
DefinitionTuple = namedtuple("Definition", "word word_id text pos")


class Word(object):

    def __init__(self, word, defs=None):
        """"""
        self.definitions = []       
        self.word = word

        if defs != None:
            for each in defs:
                try:
                    each.pos
                    if each.word.lower() == self.word.lower():
                        self.definitions.append(each)
                except AttributeError:
                    raise AttributeError("Definitions must be named tuples")

            self.orderDefinitions()


    def orderDefinitions(self):
        """"""  
        ordered = sorted(self.definitions, key=lambda definition: definition.pos)
        for i,each in enumerate(ordered):
            each.pos = (i+1)

        self.definitions = ordered


class Definition(object):
    """"""
    def __init__(self, definition):
        """Incoming arg is a single namedtuple"""       
        self.word = definition.word
        self.word_id = definition.word_id
        self.text = definition.text
        self.pos = definition.pos       


if __name__ == "__main__":
    nt1 = DefinitionTuple("dissemble", 5, "text_string_a", 1)
    nt2 = DefinitionTuple("dissemble", 5, "text_string_b)", 2)
    nt3 = DefinitionTuple("dissemble", 5, "text_string_c", 3)   

    # Definiton objects
    def_1 = Definition(nt1)
    def_2 = Definition(nt2)
    def_3 = Definition(nt3)



    dissemble = Word("dissemble", [def_1, def_2, def_3])
    print "first printing: "
    for each in dissemble.definitions:
        print each.pos, each.text

    # create a new instance of Word ...
    a_separate_instance = Word("dissemble", [def_3])    

    # ... and now the 'pos' ordering of my first instance is messed up!
    print "\nnow note how numbers differ compared with first printing:"     
    for each in dissemble.definitions:
        print each.pos, each.text

【问题讨论】:

    标签: python oop object


    【解决方案1】:

    您创建了一个 Word 的新实例,但您重复使用了 def_3 的同一个实例:

    a_separate_instance = Word("dissemble", [def_3])    
    

    这是有状态的。如果我们使用vars查看内部:

    print vars(def_3)
    # create a new instance of Word ...
    a_separate_instance = Word("dissemble", [def_3])    
    print vars(def_3)
    

    我们看到

    {'text': 'text_string_c', 'word': 'dissemble', 'pos': 3, 'word_id': 5}
    {'text': 'text_string_c', 'word': 'dissemble', 'pos': 1, 'word_id': 5}
    

    由于orderDefinitions

    【讨论】:

    • 谢谢。没见过vars用过,可以派上用场。
    【解决方案2】:

    在您的orderDefinitions 方法中,您正在修改Definition 对象的pos 属性:

    each.pos = (i+1)
    

    所以当您第二次调用orderDefinitions 时,您将调用def_3.pos = 1

    但是,dissemble 持有对此 def_3 对象的引用,其 pos 属性现已更改,因此您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多