12

Hi everyone this is probably something extremely simple that i'm overlooking but can someone point me in the right direction for how to handle this problem.

def nodeFunction(self,*args):
    return self[1] + self[2]    

Basically what I am trying to do is grab the data passed in through the arguments. I am just stuck on the syntax for referencing the arguments inside the function when using *args.

ljk321
  • 16,242
  • 7
  • 48
  • 60
SacredGeometry
  • 863
  • 4
  • 13
  • 24
  • A neat rule of thumb in Python is that names have to come from somewhere; they don't get magically inserted by the language. (An instance method refers to the instance as `self` only because that is the first argument to the method -- there's no magic `this`. A setter for a property refers to the value it is setting as an argument -- there's no magic `value`. If you want to use a function inside a module `foo`, you have to import `foo` so that the interpreter knows what it is. Etc.) – Katriel Jul 30 '11 at 13:58

2 Answers2

24

args is simply a tuple:

def nodeMethod(self, *args):
    return args[0], args[1]

Is that what you mean?

Note that there's nothing special about "args". You could use any variable name. It's the * operator that counts.

>>> class Node(object):
...     def nodeMethod(self, *cornucopia):
...         return cornucopia[0], cornucopia[1]
... 
>>> n = Node()
>>> n.nodeMethod(1, 2, 3)
(1, 2)

Still, "args" is the most idiomatic variable name; I wouldn't use anything else without a good reason that would be obvious to others.

Karl Sebby
  • 43
  • 4
senderle
  • 145,869
  • 36
  • 209
  • 233
  • Bloody hell, I am such an idiot, sorry im still getting the hang of python. Thats exactly what I was looking for thank you. Ill accept the answer when I can. – SacredGeometry Jul 30 '11 at 12:21
5
def nodeFunction(self, arg1, arg2, *args)

*arg in argument list means: pass the remaning arguments as a list in variable arg. So check how to handle lists. Note: list index starts from 0.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176