Type emulation issues with new style classes

Michael Hudson mwh at python.net
Mon Mar 1 12:13:27 CET 2004


"Chris" <feb04.20.netman at spamgourmet.com> writes:

> I tried a couple variation of that, and __getattr__, when defined in a
> metaclass is never called when accessing an attribute on an instance of a
> class derived from that metaclass.
> 
> Here is some testing I did:
> 
> class Zmeta(type):
>     def __getattribute__(*args):
>         raise Exception('called __getattribute__ with %s' % str(args))
>     def __getattr__(*args):
>         raise Exception('called __getattr__ with %s' % str(args))
> 
> Z = Zmeta('Z', (), {'value': 42})
> z = Z()
> 
> >>> int(z)
> TypeError: int() argument must be a string or a number
> >>> z.__int__
> AttributeError: 'Z' object has no attribute '__int__'
> >>> Z.__int__
> Exception: called __getattribute__ with (<class '__main__.Z'>, '__int__')
> 
> It appears (and is confirmed in: Metaclass Programming in Python Pt. 2
> http://www-106.ibm.com/developerworks/library/l-pymeta2/?ca=dnt-434) that
> metaclass attributes are available to instances (classes) but not instances
> of instances.

Argh.  Yes, now I think about the implementation, this isn't that
surprising.  OTOH, one shouldn't have to know Objects/typeobject.c as
well as I do to avoid being surprised by Python...

I've added some more detailed comments to the bug report Michele
mentioned, if you're curious.

Cheers,
mwh

-- 
  SCSI is not magic. There are fundamental technical reasons why it
  is necessary to sacrifice a young goat to your SCSI chain now and
  then.                                                  -- John Woods



More information about the Python-list mailing list