Question: Error or misconcept

Emile van Sebille emile at fenx.com
Mon Nov 5 20:23:29 CET 2001


"Károly Ladvánszky" <aa at bb.cc> wrote in message
news:3be69dd1_5 at corp-goliath.newsgroups.com...
> Thanks indeed, all clear now. It has really been a misconcept of mine.
> Could you perhaps help me with the __dict__ question?

To restate the question:

> Processing the object's __dict__ special attribute seemed to be a good
> choice.
>
> It works fine for the class:
>
> class c1:
>     a1=0
>     def f1(self,a):
>         self.a1=(a)
>
> c1.__dict__  ==> {'__doc__': None, '__module__': '__main__', 'f1':
<function
> f1 at 012E0BFC>, 'a1': 0}
>
> Trying to use it for an object results in an empty dictionary:
>
> o1=c1()
> o1.__dict__  ==> {}
>
> Referring to an attribute of o1 through the dictionary seems to sortof
> refreshing the dictionary:
>
> o1.__dict__['a1']=2
> o1.__dict__ ==> {'a1': 2}
>
> Is it a misconcept of mine about __dict__? If it is, what's the right way
to
> enlist an arbitrary object's attributes, methods?

Generally, dir(obj) is a good place to start, as it considers more that just
__dict__.  But, be careful with introspection.  There is a difference
between attributes of an object, and what that object can return.  Consider
the following:

>>> class C: pass
...
>>> def gg (self,var):
...     try:
...             return globals()[var]
...     except KeyError:
...             raise AttributeError, var
...
>>> C.__getattr__ = gg
>>>
>>> c = C()
>>> c.i
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in gg
AttributeError: i
>>> i = 12
>>> c.i
12
>>> dir(c)
[]
>>> c.__dict__
{}
>>> c.__class__
<class __main__.C at 84a790>

The same way that c.i returned 12 when i was not found in dir or __dict__ of
c or C, __class__ appears as an attribute of c.

If you want to seriously get into introspection, learn from the relevant
sections of code that attempt it.  IIRC, most of the python ide's provide
this ability.

Remember though, to quote Guido from earlier this summer when asked of the
possibility of some form of:

> def attrs(x):
> 	return [y for y in all_possible_strings if hasattr(x, y)]

Guido replied:

In general, this is as impossible as it ever was -- you won't be able
to tell *for sure* whether an object has an attribute x, since
__getattr__ may be dynamic.

<http://groups.google.com/groups?selm=cpwv4syrzd.fsf%40cj20424-a.reston1.va.
home.com>


> What is 'Bases-search-order-subject-to-python-release-ly y'rs' ?
>

Look up the section titled _MRO: Method resolution order (the lookup rule)_
in PEP 253 at http://python.sourceforge.net/peps/pep-0253.html for a
detailed description of this change.

HTH,

Emile van Sebille
emile at fenx.com





More information about the Python-list mailing list