Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where should I define functions that i use in __init__

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?

like image 224
jonathan topf Avatar asked Aug 21 '12 11:08

jonathan topf


People also ask

Can you call functions in init python?

You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method. The __str__ method is called when you print() an object. On the other hand, user-defined methods, like stefi.

What is the correct syntax for defining an __ Init__?

We can declare a __init__ method inside a class in Python using the following syntax: class class_name(): def __init__(self): # Required initialisation for data members # Class methods … …

What is def __ init __( self?

The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the object's state. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created.

Is __ init __ necessary in Python?

__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor. The __init__ method can be called when an object is created from the class, and access is required to initialize the attributes of the class.


1 Answers

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.

like image 102
sloth Avatar answered Nov 10 '22 01:11

sloth