Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use *args in a python class?

I am trying to get some args working in a class, I already got it running in a function from How to use *args in a function?.

I'm trying to get that function into a class but I don't seem to understand how to initialize that class which has an init function taking *args. The code is as following :

class classname(object):
    def __init__(self, *args):
        <code-snip>
        ...
        </code-snip>

if __name__ == "__main__":
    start = classname()
    start()

So here I'm confused on what to do with 'start()'. Do I have to use 'start(*sys.argv[1:])' or 'start()'. Both doesn't seem to work. I want to get the *args which is expected in init to be passed properly.

Any pointers please.

Thanks a ton..

======

I'm sorry if I wasn't clear on detailing how it didn't work.

a) While using start(*sys.argv[1:])

Traceback (most recent call last):
  File "check.py", line 126, in <module>
    start(*sys.argv[1:])
TypeError: 'check' object is not callable

b) While using start(), I get :

Traceback (most recent call last):
  File "check.py", line 126, in <module>
    start()
TypeError: 'check' object is not callable

These were the errors which came up.

@alko, yes you are correct. I was looking on how to get the *args in init passed properly.

like image 712
vimal Avatar asked Oct 17 '25 01:10

vimal


1 Answers

Objects are instantiated by passing arguments to class constructor. They are in turn initalized with __init__ function. In your example this would be

start = ClassName(*sys.argv[1:])

that expression is processed as follows:

  1. New instance of classname is instantiated with object.__new__(ClassName, *sys.argv[1:]) named start in local namespace. From now on start object may be referenced inside your if __name__ == "__main__" script.
  2. Its contents are in turn initialized invoking start.__init__(*sys.argv[1:]). Note that args to __init__ are the same passed to constructor.

And read PEP 8 for python naming convention. That is:

Class names should normally use the CapWords convention.

like image 108
alko Avatar answered Oct 19 '25 13:10

alko