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 = 1
First, you are right--these two items of code do effectively the same thing for your purposes (specifically because we're working with int
objects 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.
class main(object):
x = 1
class main(object):
def __init__(self):
self.x = 1
This is why many non-standard Python libraries, like mongoengine
and django
models, 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:
class mymodel(models.model):
name = models.CharField(max_length=20)
url = models.UrlField()
However, as the other poster points out, there is a difference between the two in that when x=1
is 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 Person
class, and when we create a Person
, we supply their age, and then their birth year is automatically calculated from that for us.
import datetime
class Person(object):
def __init__(self, age):
self.age = age
self.birth_year = (datetime.date.today() - datetime.timedelta(days=age*365)).year
In use:
>>>joe = Person(23)
>>>joe.age
23
>>>joe.birth_year
1990
This wouldn't be possible without __init__
, since we couldn't pass the initialization the age
argument otherwise.