Are all classes new-style classes in 2.4+?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Dec 31 08:28:21 EST 2006


On Sun, 31 Dec 2006 03:57:04 -0800, Isaac Rodriguez wrote:

> Hi,
> 
> This is probably a very basic question, but I've been playing with new
> style classes, and I cannot see any difference in behavior when a
> declare a class as:
> 
> class NewStyleClass(object):
> 
> or
> 
> class NewStyleClass:
> 
> I declare property members in both and it seems to work the exact same
> way.

Then you aren't looking very closely. Try with a calculated property.

>>> class New(object):
...     def __init__(self):
...             self._n = 1
...     def getter(self):
...             return "spam " * self._n
...     def setter(self, n):
...             self._n = n
...     spam = property(getter, setter, None, None)
...
>>> obj = New()
>>> obj.spam
'spam '
>>> obj.spam = 3
>>> obj.spam
'spam spam spam '
>>> obj.spam = 7
>>> obj.spam
'spam spam spam spam spam spam spam '

Now try with an old-style class.

>>> class Old:
...     def __init__(self):
...             self._n = 1
...     def getter(self):
...             return "spam " * self._n
...     def setter(self, n):
...             self._n = n
...     spam = property(getter, setter, None, None)
...
>>> obj = Old()
>>> obj.spam
'spam '
>>> obj.spam = 3
>>> obj.spam
3

Properties should not be used with old-style classes because they just
don't work correctly.



-- 
Steven.




More information about the Python-list mailing list