3

How can it be that this test case

import unittest

class PropTest(unittest.TestCase):
    def test(self):
        class C():
            val = 'initial val'

            def get_p(self):
                return self.val

            def set_p(self, prop):
                if prop == 'legal val':
                    self.val = prop

            prop=property(fget=get_p, fset=set_p)

        c=C()
        self.assertEqual('initial val', c.prop)

        c.prop='legal val'
        self.assertEqual('legal val', c.prop)

        c.prop='illegal val'
        self.assertNotEqual('illegal val', c.prop)

fails as below?

Failure
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 279, in run
    testMethod()
  File "/Users/jacob/aau/admissions_proj/admissions/plain_old_unit_tests.py", line 24, in test
    self.assertNotEqual('illegal val', c.prop)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 358, in failIfEqual
    (msg or '%r == %r' % (first, second))
AssertionError: 'illegal val' == 'illegal val'
Machavity
  • 30,841
  • 27
  • 92
  • 100
Jacob
  • 188
  • 1
  • 4
  • 13
  • Duplicate: http://stackoverflow.com/questions/2240351/python-2-6-4-property-decorators-not-working –  Mar 17 '10 at 04:07
  • This is a legitimate criticism that the error message sucks when you try to use `property` but forgot new-style class/must inherit from *`Object`*. IDEs could catch this one. – smci Aug 13 '12 at 19:23

1 Answers1

13

Your class C does not inherit from object or any other new-style class, so it is an old-style class (and therefore does not support properties). Descriptors are for new-style classes only. To fix, change class C() to class C(object).

http://www.python.org/download/releases/2.2.3/descrintro/ provides some details, if you are interested. New-style classes are better in several ways.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
  • Thanks Mike. That was fast. I had just stumbled on the same answer here as well: http://stackoverflow.com/questions/2240351/python-2-6-4-property-decorators-not-working – Jacob Mar 17 '10 at 03:26