When should I use __init__ in functions within classes?

7

From the book I'm studying, at times the author uses __init__ as being a first function of a class. This function (and others) always have self as one of the variables (something that I still do not understand why). When should (and why) use __init__ functions within (some) classes?

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

class Batata(object):

Is this object mandatory at some point? If so, when?

    
asked by anonymous 19.01.2016 / 03:04

1 answer

8

You're right. OOP is more complicated than it sounds. Most people learn wrong and die doing wrong. I started to learn in the 80's and until today I have doubts if I'm doing it right. Poorly done OOP can be worse than another well-done paradigm.

In this particular case you do not have much difficulty. This is the object builder . It is used to initialize the object when it will create an instance of that class. It's a weird way of doing this, but it's the Python way.

self is a required parameter that will receive the created instance. Unlike many languages, it must be explicit. And also unlike many languages that create the object during the constructor, Python creates the object and passes it to the complementary constructor 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)

Documentation .

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

    
19.01.2016 / 03:23