Possible Duplicate:
Variables inside and outside of a class __init__() function
I understand that when a class is called it will run the code in __init__ before anything. I still don’t see the difference between that, and writing the code directly under the class.
For example:
class main():
x = 1
def disp(self):
print self.x
class main():
def __init__(self):
self.x = 1
def disp(self):
print self.x
To me, both have the same functionality. (Maybe I am missing out something.) I would like to know which is more (ahem) pythonic and why.
There are a couple key differences here, both between
__init__and writing it just under the class, as well as what you wrote.Working with
x = 1First, you are right–these two items of code do effectively the same thing for your purposes (specifically because we’re working with
intobjects here, this would be different for mutable objects):Note that they don’t actually do the same thing–please see the comments on this answer for clarification.
This is why many non-standard Python libraries, like
mongoengineanddjangomodels, have a standard where you create classes without using an__init__statement so as not to override the built-in one, but still allowing you to create class attributes, e.g., a Django example:However, as the other poster points out, there is a difference between the two in that when
x=1is outside of the__init__function, it is part of the class itself even when not intialized–see Zagorulkin Dmitry‘s answer for more detail on that. In most cases, though, that distinction won’t be relevant for you.Other considerations
There are more uses for
__init__beyond just setting variables. The most important one offhand is the ability to accept arguments during initialization. To my knowledge, there is not a way to do this without an__init__function. I’ll show you what I mean by this in this example.Let’s say we’re creating a
Personclass, and when we create aPerson, we supply their age, and then their birth year is automatically calculated from that for us.In use:
This wouldn’t be possible without
__init__, since we couldn’t pass the initialization theageargument otherwise.