Search code examples
pythonoopargs

How to handle magic variables in a constructor of a Class


I need a magic variable in my class and started writing it

class myclass:
    def __init__(self, name, *args):
        self.name = name
        ????

    def myFunc()
        for i in args:
            print(i)

I just could not find a proper explanation of how to write a class with magic variables in the constructor and use it later. Do I have to create a self. member out of it (and if so how) or can I neglect it and just use args as in myFunc ?


Solution

  • *args are not called magic variables, but arbitrary argument lists, or variadic arguments, and they are used to send arbitrary number of arguments to a function, and they are wrapped in a tuple like the example below

    In [9]: def f(a,*args): 
       ...:     print(a) 
       ...:     print(args) 
       ...:                                                                                                                                                                           
    
    In [10]: f(1,2,3,4)                                                                                                                                                               
    1
    (2, 3, 4)
    

    So in order to access these variables, you would do what you do for any class instance variable, assign it via self.args = args and access them via self.args

    Also note that we use camel-case for class names, so the class name changes to MyClass and snake-case for functions, so the function name changes to my_func

    class MyClass:
        def __init__(self, name, *args):
            self.name = name
            #Assigning variadic arguments using self
            self.args = args
    
        def my_func(self):
            #Accessing variadic arguments  using self
            for i in self.args:
                print(i)
    
    
    obj = MyClass('Joe',1,2,3)
    obj.my_func()
    

    The output will be

    1
    2
    3