Reputation: 8367
I'm writing a class that makes use of some functions inside its __init__
function and I'm not sure about the best practice of where to define those functions. I usually like to define __init__
first but if I need to use the a function/method within the __init__
then it needs to be defined first. I dont want to define it outside the class as its useless outside the class but it seems messy to me to define methods before the __init__
. What are the normal conventions for this?
Upvotes: 12
Views: 14451
Reputation: 20339
Why should it be 'messy' to define methods after the init ? Think about it that way :
When you define
class MyClass(object):
def __init__(self):
self.something = whatever
self.do_something_else()
def do_something_else(self):
...
__init__
is a method of your MyClass
class, just like do_something
is; it's just the first method of the class that will be called when you create an instance of MyClass
. So, putting __init__
first is not only customary but also logical.
Your do_something_else
method doesn't have to be defined first because you use it in __init__
. From the point of view of MyClass
, it's a method like another. When you create your myclass=MyClass()
instance, do_something_else
has already been defined...
Upvotes: 0
Reputation: 3695
It's better to define __init__
function as first function, and you can call functions defined after __init__
inside it.
class A:
def __init__(self):
print self.x()
def x(self):
return 10
Upvotes: 2
Reputation: 10477
The normal convention is indeed to put __init__
before other methods. The reason this works is that functions aren't evaluated until invoked. From the Python docs:
A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.
The function definition does not execute the function body; this gets executed only when the function is called.
Upvotes: 4
Reputation: 101052
Just add the methods to your class like every other method
class Test(object):
def __init__(self):
self.hi()
def hi(self):
print "Hi!"
No problem at all.
While it is not mentioned in the Python Style Guide IIRC, it's convention to let __init__
be the first method in your class.
Upvotes: 19