Reputation: 25
class MyClass(object):
class_var = []
def __init__(self, i_var):
self.i_var = i_var
a = MyClass(2)
a.hit = 1
print a.hit
As we can see, hit
is added to a
as an instance variable after initialization.
What's a good reason to allow defining instance variable in such a way? And, is it dangerous?
Upvotes: 1
Views: 265
Reputation: 514
I think it's just consistent with the python principle that ''we are all responsible users''. See here: http://docs.python-guide.org/en/latest/writing/style/
Upvotes: 1
Reputation: 15105
There is no good answer to "why?" question. This is part of python ideology. Python incorporates elements from several different programming paradigms to accommodate different coding styles. You can write functional, pure object oriented, structured (if you are old and not very bright) or even event driven if you want to be extra fancy and asynchronous. It is not inherently dangerous, but like many other language niceties it does allow you to shoot yourself (and possibly other members of your development team) in the proverbial foot.
Upvotes: 2
Reputation: 309889
What's a good reason to allow defining instance variable in such a way?
I think it's important to note that self
inside your __init__
function is exactly the same as self
in any other method on that instance. It's also the same as a
outside the class. The magic of the __init__
method lies in when it gets called and nothing else (which is true of all python magic methods). To have __init__
"freeze" the object in one way or another would go against the way things have always been done in python.
So, I would say that the "good reason" is because it makes things very consistent.
And, is it dangerous?
Yes. It can be.
The practice of intentionally adding methods/attributes to an instance is known as Monkey Patching (also occasionally called Duck Punching)1 -- And it really shouldn't be done unless you don't have any other options.
The practice of unintentionally adding methods/attributes to an instance is known as creating bugs (and we've all done it :-).
Fortunately, there are tools to help you prevent these types of bugs. Linters are the most common. I personally use pylint
to help warn me about these sorts of bugs.
Between the linter and using common sense (see above about not Monkey Patching), I've very rarely been hit with a hard-to-track bug because of this part of python's ideology.
1I suppose that it isn't duck punching if you add more attributes in a later instance method -- But you probably shouldn't be doing that either . . .
Upvotes: 4