请考虑以下类定义
class of2010(object):
def __init__(self):
self._a = 1
self._b = 2
self._c = 3
def set_a(self,value):
print('setting a...')
self._a = value
def set_b(self,value):
print('setting b...')
self._b = value
def set_c(self,value):
print('setting c...')
self._c = value
a = property(fset=self.set_a)
b = property(fset=self.set_b)
c = property(fset=self.set_c)
Run Code Online (Sandbox Code Playgroud)
请注意set_[a|b|c]()做同样的事情.有没有办法定义:
def set_magic(self,value):
print('setting <???>...')
self._??? = value
Run Code Online (Sandbox Code Playgroud)
一次,并将其用于a,b,c如下
a = property(fset=self.set_magic)
b = property(fset=self.set_magic)
c = property(fset=self.set_magic)
Run Code Online (Sandbox Code Playgroud) 怎么可能是这个测试用例
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)
Run Code Online (Sandbox Code Playgroud)
失败如下?
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, …Run Code Online (Sandbox Code Playgroud)