2

I'm trying (because I think it should exists) to define a class but it would receive a tuple as an input.

What I mean is:

class Class_name:
    def __init__(self, (a,b)):

but it obviously generates an error. I don't know, just think I want to plot many complex numbers that I have written in a two-column list its real part and imaginary part. I know I can unpack, but I want to know if there is a way of doing it directly so i cant write (1,2) as an input, not 1,2. Thanks!

UnPerrito
  • 45
  • 9
  • Does this answer your question? [Expanding tuples into arguments](https://stackoverflow.com/questions/1993727/expanding-tuples-into-arguments) – mkrieger1 Mar 12 '20 at 19:48
  • 1
    Just use `def __init__(self, a, b)` and then call `Class_name(*the_tuple_containing_a_and_b)`. – mkrieger1 Mar 12 '20 at 19:49
  • 1
    Python has a `complex` type for complex numbers. Consider the output of `list(map(complex, [1,2,3], [4,5,6]))`. – chepner Mar 12 '20 at 20:21

1 Answers1

2

You have three options depending on what you're trying to accomplish exactly

One parameter

You can unpack in __init__ if needed

class MyClass:
    def __init__(self, t):
        self.a, self.b = t

foo = (1, 2)
MyClass(foo)

Two parameters

You can unpack when instantiating if needed

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

foo = (1, 2)
MyClass(*foo)

Native complex type

class MyClass:
    def __init__(self, a):
        self.a = a

foo = 1+2j  # Equivalent to "complex(1, 2)"
MyClass(foo)
wjandrea
  • 28,235
  • 9
  • 60
  • 81