Extending Python: rewriting a single method in C

Jacek Generowicz jmg at ecs.soton.ac.uk
Wed Mar 14 11:26:10 CET 2001


"Alex Martelli" <aleaxit at yahoo.com> writes:

> "Jacek Generowicz" <jmg at ecs.soton.ac.uk> wrote in message
> news:g0lmq9xxz0.fsf at scumbag.ecs.soton.ac.uk...
>     [snip]
> > As I understand it, I have to provide a __getattr__ method in my
> > python class which will get called when I use PyObject_GetAttr. (If
> > this is so then I don't see why the function isn't automatically
> > provided; any creative definition---ie differing from the blatantly
> > obvious (and hence tedious)---surely only opens the door to
> > horrors. Still, mine is not to reason why.)
> 
> You need only provide __getattr__ if you have to do something
> special -- and when you do need it, it's nice to have the ability.
> But attribute-getting works just fine for simple cases without
> you writing anything special!

That's what I thought until I tried something like the following:

>>> class foo:
...     def __init__ ( self, a ):
...             self.bar = a
...     def show ( self ):
...             print self.bar
... 
>>> a = foo( 4 )
>>> a.show()
4
>>> print a.__getattr__("bar")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'foo' instance has no attribute '__getattr__'

So I had a look at some documentation. Let me quote Beazley, page 30:

  a = x.s     # Invokes __getattr__(x,"s")

You never know, strager things have happened, let's give it a go :

>>> z = __getattr__(foo,"bar")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: There is no variable named '__getattr__'

Hmmmmm.

OK . . . I guess this means that the default implementation is not
accessible via __getattr__, but it is available via PyObject_GetAttr ?



  [Useful references to relevant documentation snipped]

> > (Would it be fair to say that the documentaion is, on the whole, less
> > that satisfactory ?)
> 
> I find it pretty decent, myself.

I guess that it is if you know what you are looking for and where to
find it :-)


Cheers,

Jacek



More information about the Python-list mailing list