Reputation: 403
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.
Upvotes: 4
Views: 8430
Reputation: 48317
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:
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.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.
Upvotes: 8
Reputation: 91059
Your example contains a class which is first instantiated - which involves calling __init__()
- and then called - which is done by calling __call__()
.
So your stuff should be put in the call start = classname(...)
in order to be passed to __init__()
.
The call to the newly instantiated object will fail, however, unless it contains a __call__()
method. That would have been easier to answer if you had told us what
Both doesn't seem to work.
exactly means.
Upvotes: 0