UnPerrito
UnPerrito

Reputation: 155

Initialize a class with a tuple as input

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!

Upvotes: 2

Views: 2806

Answers (1)

wjandrea
wjandrea

Reputation: 32964

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)

Upvotes: 2

Related Questions