Raising objects
Steven Taschuk
staschuk at telusplanet.net
Wed Apr 30 01:04:47 EDT 2003
Quoth Jan Olderdissen:
[...]
> That said, I question the point of deriving from object as classes
> (and in fact all objects as far as I can tell) are derived from object
> as it is. [...]
Depends what you mean by "derived". On the one hand, both old-
and new-style instances are instances of object according to
isinstance():
>>> class OldStyle: pass
...
>>> class NewStyle(object): pass
...
>>> o = OldStyle()
>>> n = NewStyle()
>>> isinstance(o, object)
1
>>> isinstance(n, object)
1
But on the other hand, old-style classes are not subclasses of
object:
>>> issubclass(OldStyle, object)
0
>>> issubclass(NewStyle, object)
1
For example, they do not inherit attributes from object:
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__']
>>> n.__reduce__
<built-in method __reduce__ of NewStyle object at 0x815045c>
>>> o.__reduce__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: OldStyle instance has no attribute '__reduce__'
> [...] Since object isn't a class, deriving from it probably is
> bogus to begin with. [...]
Not at all; it's exactly the right way to make a new-style class,
which is (among other things) needed to get properties to work:
Right:
>>> class NewStyle(object):
... x = property(lambda self: 3)
...
>>> n = NewStyle()
>>> n.x
3
>>> n.x = 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute
Wrong:
>>> class OldStyle:
... x = property(lambda self: 3)
...
>>> o = OldStyle()
>>> o.x
3
>>> o.x = 2 # shouldn't be able to do this!
>>> o.x
2
What *is* bogus imho is the distinction between old- and new-style
classes. (It exists for historical reasons; eventually old-style
classes will disappear, I presume and hope.)
--
Steven Taschuk "The world will end if you get this wrong."
staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide",
Brian Kernighan and Lorrinda Cherry
More information about the Python-list
mailing list