When should I use __init__ in functions within classes?

Asked

Viewed 25,589 times

19

For the book I am studying, in some moments the author uses __init__ as a first function of a class. This function (and others) always has self as one of the variables (something I haven’t yet understood why). When should I (and why) use functions __init__ within (some) classes?

When I create a parental class or even a class that will not have hierarchy relations between it and other classes, I am obliged to name it as:

class Batata(object):

That one object is required at some point? If yes, when?

  • 1

    Separate into two questions. Here we keep things organized. Each question should have only one question. Unless it was completely related, which is not the case. They are subjects of the same area but distinct.

  • Actually not accurate, the question has already been answered elsewhere. See the answer.

  • Okay. Thanks for the tip. I’ll be more careful on the next question.

1 answer

23


You’re right. OOP is more complicated than it looks. Most people learn wrong and die doing wrong. I started apender in the 80’s and even today I have doubts if I’m doing it right. OOP poorly done can be worse than another paradigm well done.

In this particular case there is not much difficulty. This is the object builder. It is used to initialize the object when creating an instance of that class. It is a weird way to do this, but it is the Python way.

The self is a mandatory parameter that will receive the created instance. Unlike many languages, it must be explicit. And also unlike many language that create the object during the constructor, Python creates the object and passes it to the constructor complement with the first necessary actions when it is built.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

x = Point(1, 2)
print(x.x)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation.

The second part of the question has already been answered here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.