Search code examples
pythonargs

Check the content of *args in a Class __init__


I want to test if in the *args parameter is a string ti. If so I want to print "ti". If it is a list where the first element has a length of 1 I want to print "it is a list with len 1 values". If both does not apply, I want to print "full list"

Here is my code it does not print anything and I do not know why. Can anyone help me here?

class MyClass:
    def __init__(self, *args):
        self.args = args

    def test_meth(self):

        if self.args == 'ti':
            print('ti')
        elif type(self.args) == list:
            if len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')

my_class = MyClass('ti')
my_class.test_meth()

Solution

  • *args in def __init__(self, *args): will lead self.args to store a tuple so the first if-statement will always be False. If you want your code to work, you should rewrite it as:

    class MyClass:
        def __init__(self, *args):
            self.args = args
    
        def test_meth(self):
            if self.args == ('ti',):
                print('ti')
            elif len(self.args) == 1 and len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')
    
    my_class = MyClass('ti')
    my_class.test_meth()
    

    or with more generic (works with any iterable args):

    class MyClass:
        def __init__(self, *args):
            self.args = args
    
        def test_meth(self):
            if len(self.args) == 1 and self.args[0] == 'ti':
                print('ti')
            elif len(self.args) == 1 and len(self.args[0]) == 1:
                print('it is a list with len 1 values')
            else:
                print('full list')
    
    my_class = MyClass('ti')
    my_class.test_meth()