[Tutor] Option of passing sequences are arguments
Steven Burr
sburr@mac.com
Sun, 17 Jun 2001 22:44:20 -0700
On Friday, June 15, 2001, at 03:53 PM, Phil Bertram wrote:
> Is it possible to unpack a sequence to fill arguments.
> I have been playing around with *args type aruments but can't seem to
> get it
> to work.
>
> Eg
>
> I would like to define a class so that it can be called as follows
>
> m = MyObject(arg1,arg2,arg3)
>
> or
>
> args=(arg1,arg2,arg3)
> x=MyObject(args)
I think this may be the kind of thing you're looking for (the __str__
method is just
for testing purposes):
import types
class MyObject:
def __init__(self, *args):
if len(args) == 1 and type(args[0]) != types.StringType:
try: test = args[0][0]
except TypeError: self.args = args
else: self.args = args[0]
else: self.args = args
def __str__(self):
return ' '.join([str(x) for x in self.args])
a = MyObject("It's", 'only', 'a', 'flesh', 'wound!')
print a
args = ("I've", 'had', 'worse.')
b = MyObject(args)
print b
c = MyObject("You're a loony!")
print c
d = MyObject(1)
print d
RESULT:
It's only a flesh wound!
I've had worse.
You're a loony!
1