too dynamic - how to avoid?

Denis S. Otkidach ods at strana.ru
Thu Oct 2 06:46:16 EDT 2003


On Thu, 2 Oct 2003, mic wrote:

m> I've spent last hour trying to debug my code, when I found
m> out that instead
m> of executing object's method I accidentaly overridden it with
m> variable (see
m> below example). My stupid! But as the system becomes more
m> complex, I begun
m> to wonder how to avoid such situations in the future. Does
m> anybody have some
m> experiences about that?
m>
m> Simple example:
m>
m> class test:
m>     def a(self, value):
m>         print value
m> t = test()
m> t.a('my test') <= returns obviously 'my test'
m> t.a = 'my test' <= creates object's attribute a, so I'm
m> loosing my method

Try using slots:
>>> class test(object):
...     __slots__ = []
...     def a(self, value):
...         print value
...
>>> t = test()
>>> t.a('my test')
my test
>>> t.a = 'my test'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'test' object attribute 'a' is read-only
>>> t.a('my test')
my test

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]






More information about the Python-list mailing list