Very simple request about argument setting.

Fredrik Lundh fredrik at pythonware.com
Mon Oct 30 01:59:42 EST 2006


Hakusa at gmail.com wrote:

> ArdPy wrote:
>> There is an error in the syntax the star must prefix the variable name
>> not suffix it.
>> Then the items variable will accept the parameter value as a tuple.
> 
> Hmm, tuples are immutable, right? I need something mutable so that when
> the player picks up an item, it's no longer in the room.

the *args syntax is used to capture extra positional arguments, so you 
can deal with them later.  consider the following code:

     def func(*args):
         args.append(4)

     func(1, 2, 3)

where do you expect the "4" to go?

if you want to *store* the items in an *instance* variable, you can 
trivially convert it to a list by passing it to the list() function:

     class Room:
       def __init__(self, name, *items):
         self.name = name
         self.items = list(items)

     r = Room("hall", "old shoe", "kitten", "vegetables")
     r.items.append("a wallclock round in metal")

> Besides which, I've been playing with this whole thing in the
> interactive interpreter:
> 
>>>> def shuf(x,*foo, **bar):
> ... 	return x, foo
> ...
>>>> x,foo,bar = shuf(1,2,3,4,5,6,7,8)
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in <module>
> ValueError: need more than 2 values to unpack

if you compare the return statement inside the function with the 
assignment, do you see any notable differences?

> I remember that two stars is for the second tuple

if you're an expert on tutorials, surely you should be able to find one 
and look this up in no time at all?

(the **bar syntax captures extra *keyword* arguments)

> So what I am doing wrong?

programming by trial and error?

</F>




More information about the Python-list mailing list