[Tutor] Question on the "object" object

Terry Carroll carroll at tjc.com
Thu Jan 15 03:06:37 EST 2004


in response to Todd's question in the thread "Do tuples replace 
structures?", I ended up saying:

> I prefer to use classes, though for just about anything where I need a
> structure:
>
> >>> class person:
> ...   def __init__(self,fname,lname,age,height):
> ...     self.fname = fname
> ...     self.lname = lname
> ...     self.age = age
> ...     self.height = height
> ...
> >>> record = person("Jim", "Smith", 22, 130)
> >>> record.fname
> 'Jim'

This got me wondering; how minimalist can you get in a class definition 
and still be able to access arbitrarily-named attributes?  Some toying 
around to figure that out has gotten me into something I don't understand, 
and would like to.

Now, none of the following three objects raise an Attribute error as a
result of assigning to foo.bar, a previously unreferenced attribute:

>>> #old-style class
... class c1:
...     pass
...
>>> o1=c1()
>>> o1.a="test"
>>> print "o1", o1.a
o1 test

>>> #new-style class
... class c2(object):
...     pass
...
>>> o2=c2()
>>> o2.a="test"
>>> print "o2", o2.a
o2 test

>>> #new-style class, calling object's __init__
... class c3(object):
...     def __init__(self):
...         object.__init__(self)
...
>>> o3=c3()
>>> o3.a="test"
>>> print "o3", o3.a
o3 test

Okay, so if we can do this with an instance of an object from a class that 
inherits from the "object" object, why can't we do the same with an 
instance of the "object" object itself?  (I tried several times to phrase 
that both clearly and accurately, and I'm not sure I got there; the 
example should be clearer.):

>>> #using object directly, instead of a class inherited from it
... o4=object()
>>> o4.a="test"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute 'a'


In sum, why does:

 x=object()
 x.a

raise an AttributeError, when

 x=c()
 x.a

Does note, where c is nothing more than a flat-out, no-frills subclass of 
object?





More information about the Tutor mailing list