Python assigning two variables on one line

倖福魔咒の 提交于 2019-12-18 04:48:18

问题


class Domin():
    def __init__(self , a, b) :
        self.a=a , self.b=b

    def where(self):
        print 'face : ' , self.a , "face : " ,self.b

    def value(self):
        print self.a + self.b

d1=Domin(1 , 5)   

d1=Domin(20 , 15)

I get this error:

Traceback (most recent call last):
  File "test2.py", line 13, in <module>
    d1=Domin(1 , 5)
  File "test2.py", line 5, in __init__
    self.a=a , self.b=b
TypeError: 'int' object is not iterable

回答1:


You cannot put two statements on one line like that. Your code is being evaluated like this:

self.a = (a, self.b) = b

Either use a semicolon (on second thought, don't do that):

self.a = a; self.b = b

Or use sequence unpacking:

self.a, self.b = a, b

Or just split it into two lines:

self.a = a
self.b = b

I would do it the last way.



来源:https://stackoverflow.com/questions/16747599/python-assigning-two-variables-on-one-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!