是否更好地实例化新对象,或者只是更新新数据的属性?

时间:2012-12-28 01:26:56

标签: python python-2.7

更新属性或仅实例化新对象更有效吗?

例如:

class Position(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def update_position(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def new_Position(self, message):
        self.update_position(message[0], message[1], message[2])

def new_Position(message):
    return Position(message[0], message[1], message[2])

1 个答案:

答案 0 :(得分:1)

您不应该进行过早优化,更新方法和某种工厂功能之间的选择主要是设计选择。

无论如何,出于好奇,这是两个电话之间的disassembled代码:

>>> p = Position(1,2,3)
>>> dis.dis(p.new_position)
 11           0 LOAD_FAST                0 (self)
              3 LOAD_ATTR                0 (update_position)
              6 LOAD_FAST                1 (message)
              9 LOAD_CONST               1 (0)
             12 BINARY_SUBSCR       
             13 LOAD_FAST                1 (message)
             16 LOAD_CONST               2 (1)
             19 BINARY_SUBSCR       
             20 LOAD_FAST                1 (message)
             23 LOAD_CONST               3 (2)
             26 BINARY_SUBSCR       
             27 CALL_FUNCTION            3
             30 POP_TOP             
             31 LOAD_CONST               0 (None)
             34 RETURN_VALUE        
>>> dis.dis(new_position)
  2           0 LOAD_GLOBAL              0 (Position)
              3 LOAD_FAST                0 (message)
              6 LOAD_CONST               1 (0)
              9 BINARY_SUBSCR       
             10 LOAD_FAST                0 (message)
             13 LOAD_CONST               2 (1)
             16 BINARY_SUBSCR       
             17 LOAD_FAST                0 (message)
             20 LOAD_CONST               3 (2)
             23 BINARY_SUBSCR       
             24 CALL_FUNCTION            3
             27 RETURN_VALUE