In [1]:
import re
In [2]:
class Foo(object):
@property
def bar(self):
return self.x
@bar.setter
def bar(self, x):
self.x = 3 * x
In [3]:
foo = Foo()
foo
Out[3]:
In [4]:
foo.bar = 'world'
In [5]:
foo.bar
Out[5]:
In [6]:
goo = Foo()
goo
Out[6]:
In [7]:
goo.bar
The error message above is not helpful for coder, so starting with cell #9, I play with changing it to complain about 'bar' instead of complaining about 'x'.
In [8]:
goo.foo
In [9]:
class Hoo(object):
@property
def bar(self):
try:
return self.x
except AttributeError as e:
# print('old e.args', repr(e.args))
e.args = (re.sub(
r"'[A-Za-z_][A-Za-z0-9_]*'$",
"'bar'",
e.args[0]), )
e.args = (
"{class_name!r} "
"object has no attribute "
"{attribute_name!r}".format(
class_name=self.__class__.__name__,
attribute_name='bar')
, )
raise e
@bar.setter
def bar(self, x):
self.x = 3 * x
In [10]:
hoo = Hoo()
hoo
Out[10]:
In [11]:
hoo.bar