Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python assigning two variables on one line

Tags:

python

int

self

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
like image 566
tabebqena Avatar asked May 25 '13 07:05

tabebqena


People also ask

Can you declare two variables one line?

Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable are handled correctly.

How can you assign the same value to multiple variables in one line?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.


1 Answers

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.

like image 50
Blender Avatar answered Oct 31 '22 21:10

Blender