[C++-sig] Assign a value to its non-existing attribue, why it did not report a error?
Nat Goodspeed
ngoodspeed at solidworks.com
Mon Oct 16 14:26:56 CEST 2006
________________________________________
From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On
Behalf Of Qinfeng(Javen) Shi
Sent: Monday, October 16, 2006 4:25 AM
To: c++-sig at python.org
Subject: [C++-sig] Assign a value to its non-existing attribue,why it
did not report a error?
I wrapped a class, and get a instance of it, then assign a value to its
non-existing attribue. It should report a error. But it doesn't, and it
adds the non-existing attribue to it.
[Nat] In Python, it should not report an error, it should add the new
attribute. Try defining a small class in Python, creating an instance
and assigning to a previously-undefined attribute - without involving
your C++ code at all. This is the expected behavior in Python.
class Foo(object):
pass
foo = Foo()
foo.itWorks = True
I want it reports a error when user assign value to a non-existing
attribue mistakely.
[Nat] Are you sure you want it to behave differently than a native
Python object? In a pure-Python class, you could define your own
__setattr__() method: http://docs.python.org/ref/attribute-access.html
Your method could examine self.__dict__ and, if the specified attribute
isn't already there, raise an exception.
But I should add that I've never tried using the __setattr__() mechanism
with a C++ object published to Python.
More information about the Cplusplus-sig
mailing list