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

Case 1:
Obj1 = C(1,2)
print Obj1.a
print Obj1.b

Case 2:
l= [1,2]
Obj2 = C(l)
print Obj2.a
print Obj2.b

I want to initialize the object of a class with the list passed as initializer as shown in case 2 but that shows syntax error . Is there any way to do this in python ?

I found out I can use the unpacking here. Thanks for the answer. Can I do some thing like this by combining both of these things I know i just can append one more number and pass it to initialize object but is there a way to combine both these things ?

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

l= [1,2]
Obj2 = C(*l,3)


zk9099
  • 183
  • 10

3 Answers3

2

You want to use the unpack operator *

The both are strictly equivalent:

Obj1 = C(1,2)
Obj1 = C(*[1,2])
BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42
  • Please check for duplicates before answering. – quamrana Apr 12 '19 at 09:36
  • I understand this is a duplicate, but actually the OP just did not know about this operator :). But thanks for pointing out, and I should definitely link to other questions I will remove this answer soon – BlueSheepToken Apr 12 '19 at 09:56
  • 1
    Yes, you're right, the OP did not know about the operator. But now that this is a duplicate question there is a link at the top for everyone to see. Please keep this answer here so that others can see this discussion. – quamrana Apr 12 '19 at 10:42
0

you can unpack it, by *

l = [1, 2]
Obj2 = C(*l)
print(Obj2.a)
print(Obj2.b)
recnac
  • 3,744
  • 6
  • 24
  • 46
0

You have two options, either you unpack outside or inside:

Inide:

class C:
    def __init__(self, l):
        self.a, self.b = l
C([1,2])

Outside:

class C:
    def __init__(self, a, b):
        self.a = a
        self.b = b
C(*[1, 2])
Netwave
  • 40,134
  • 6
  • 50
  • 93