Accessing an instance's __init__ args from outside the class

A

Alexander Eberts

I'm new to python so appologies to the group if this question is asked
often. I'm wondering if it's possible to query an object instance to find
out what arguments the instance's __init__ function was called with from
*outside* the class's local namespace. For example, if I define a class Foo
as follows:

import sys
class Foo:
def __init__(self, *args):
print args # no problem here

....and then create an instance of Foo:
('bar', 'bleck')

Now, I'd like to be able to find out what arguments someobj was called with.
So first I tried:

but I get: "AttributeError: args"

so then I tried:

which returns an empty tuple

and then I tried:
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
KeyError: args

No dice.. Is there any way to find out what arguments an object was called
with? Are the args stored with the instance? I scoured the python faq but
there are no answers (that I could see) to this question. Any help would be
much appreciated.

yours,

Alex Eberts
 
D

Duncan Booth

Is there any way to find out what arguments an object was called
with?

Not in general.
Are the args stored with the instance?

It depends on the object type. Some objects may save some or all of the
arguments to the constructor, but it is up to each object to decide what to
do with its arguments. If you create your own class, and want to be able to
refer to the __init__ arguments after returning from __init__, then you
must save the arguments in the object.

So, for your original example you could do:
def __init__(self, *args):
self.args = args
print args # no problem here

('bar', 'bleck')
 
A

Alexander Eberts

Duncan,

Thanks for your response - much appreciated. Do you know how the python
interpreter handles *args and **kwargs passed to a class's __init__ method?
(maybe the better question is "what section in the python docs describes how
class args are handled" :)

all the best,

Alex
 
U

Ulrich Petri

Alexander Eberts said:
Duncan,

Thanks for your response - much appreciated. Do you know how the python
interpreter handles *args and **kwargs passed to a class's __init__ method?
(maybe the better question is "what section in the python docs describes how
class args are handled" :)

They are handled exactly as they would be in any other method. It seems you
have a bit of a misconception on how the __init__ method works!?

Ciao Ulrich

PS: To post an answer above the aswered text is not exactly liked on the
(use)net.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top