2

I have a python 2.6 class called Film:

class Film(Video):
    def __init__(self, title, yt_link, year):
        Video.__init__(self, title, yt_link)
        self.year = year

and also, I have a variable result which stores the string:

result = 'Toy Story','https://www.youtube.com/watch?v=fPhse4WlgEA','1995'

When I try to create an instance of the class:

toy_story = Film(result)

I get an error:

__init__() takes exactly 4 arguments (2 given)

However, when I input the string directly to Film(), there is no error.

How can I make it so that Film(result) might resolve the arguments error?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
zthomas.nc
  • 3,689
  • 8
  • 35
  • 49
  • I think it's good practice to enclose tuples like that in parentheses, even if Python would do it for you automatically. That prevents this kind of confusion. – Matthew Aug 01 '14 at 15:25

2 Answers2

2

result is a tuple. Currently you're passing the whole tuple to the first positional argument (title). Instead, you need to unpack the tuple using the "splat" or "unpacking" or "star" operator (it has a bunch of names):

toy_story = Film(*result)
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

To help you understand tuples and the star operator, consider this:

instead of doing

toy_story = Film(*result)

(as suggested by mgilson)

you could also do

toy_story = Film(result[0], result[1], result[2])

So, tuples can be treated kind of like a mini array.


Note: this isn't a better solution. It's only intended to be more readable for programmers unfamiliar with the star operator and tuples.

Community
  • 1
  • 1
Luke Willis
  • 8,429
  • 4
  • 46
  • 79