【问题标题】:python float object has not attribute 'value'python float对象没有属性'value'
【发布时间】:2015-05-23 00:02:53
【问题描述】:

我有 4 个共享变量。我正在根据正在运行的进程更新一对。以下是代码。

class App(multiprocessing.Process):
    def __init__ (self,process_id):
        multiprocessing.Process.__init__(self)
        self.process_id = process_id
   def run(self,X,Y,lock):
        while True: 
               with lock :
               #some calculations which returns x and y 
               print 'x and y returned are :',x,y
                 try:
                    X.value = x
                    Y.value = y
                 except Exception ,e:
                   print e
                 
 

if __name__ == '__main__':
    xL = Value('d',0.0)
    xR = Value('d',0.0)
    yL = Value('d',0.0)
    yR = Value('d',0.0)

    lock = Lock()

    a = A('1')
    b = B('2')
   
    process_a = Process(target = a.run, args(xL,yL,lock, ))  
    process_b = Process(target = b.run, args(xR,yR,lock, ))
   
    process_a.start()
    process_b.start()

这是输出:

x 和 y 返回:375 402

'float' 对象没有属性 'value'

任何帮助。 ?

【问题讨论】:

  • 请显示完整的错误信息。
  • 'float' 对象没有属性 'value' 这是它在我的终端上显示的内容
  • @BryanOakley ,不应该为 xL 对象分配一个值。 ?我刚刚在这里稍微修改了文档中的代码:docs.python.org/2/library/…
  • 那只是错误的最后一行。请包含完整错误消息。
  • 看起来虽然您将X 和Y 作为multiprocessing.Value (确实有value 属性)传递,但您在计算中的某处用浮点数覆盖了名称。

标签: python shared-memory python-multiprocessing


【解决方案1】:

看看我用括号中的数字注释的代码的三个部分:

   def run(self,X,Y,lock):
        while True:
               #some calculations which returns x and y 
               with lock :
                 X.value = x
                 Y.value = y

                 # (3) you now try to access an attribute of the arguments
                 # called 'value'
                 print X.value , Y.value , self.process_id


if __name__ == '__main__':
    xL = Value('d',0.0) # (1) these variables are assigned some objects that
    xR = Value('d',0.0) # are returned by the function 'Value'
    yL = Value('d',0.0) 
    yR = Value('d',0.0) 

    lock = Lock()

    a = A('1')
    b = B('2')

    # (2) now your variables are being passed to the 'a.run' and 'b.run'
    # methods
    process_a = Process(target = a.run, args(xL,yL,lock, ))  
    process_b = Process(target = b.run, args(xR,yR,lock, ))

    process_a.start()
    process_b.start()

当您跟踪代码的执行时,您可以看到它正在尝试访问函数Value 返回的任何对象中名为value 的属性。您的错误消息告诉您 Value 正在返回 float 对象,这些对象没有 value 属性。

以下其中一件事情(很可能)对您不利:

  1. Value 函数没有按照您的想法执行,它在不应该的时候返回浮点数。
  2. 在您的“一些返回 x 和 y 的计算”代码中,您使用浮点数覆盖了 X 和 Y 参数。

【讨论】:

  • 我认为你错过了根本问题。注释#some calculations which returns x and y 代表了一大段代码。我认为 OP 更有可能在代码片段中的某处为 X 或 Y 分配一个浮点数。 (我检查了multiprocessing.Value 确实有一个value 属性。他调用Value 的方式与multiprocessing.Value 的记录方式一致。)我可能错了,因为OP 已经接受了这个答案。
  • @StevenRumbalski 你是绝对正确的。我已经编辑了我的答案以包含它。
猜你喜欢
  • 2015-03-28
  • 2018-10-02
  • 2013-11-05
  • 1970-01-01
  • 2016-12-02
  • 2018-06-02
  • 2020-03-25
  • 2019-12-31
  • 2020-02-27
相关资源
最近更新 更多