I am quite new to Python and I cant seem to be able to understand this.Consider this simple Python code.
class point:
i = 34
test = point()
test.y = 45
print test.y
As you can see I instance of point called test but then did test.y = 45 when y is not a
data member of the point class. No error was thrown and the y attribute seems to have
been added to the class automatically.
Why did this happen? Isn’t this a misfeature? Or am I missing something very basic.
The same thing cannot be done with C++ and it would throw a compiler error. Any reason for this strange feature?
It is just a common thing from scripting languages. Python lets you do it, Ruby also, and in deed, you never had to pre-define your local variables. Why not also in your classes? Not only that, you can choose if the new inserted variables/functions affect only one object or all instances of that class.
People who are doing heavy things in TDD and UnitTesting love that misfeature. Actually I would even go as far as to say that C++ static typing does not reduce my programs bugs nearly as much as a language that ease my unit tests giving me exactly that.
However, if you are concerned, you can always use _____slots_____
https://stackoverflow.com/a/3603624/253098