How to determine what to put inside the __init__ function in a python class?

So, I understand how to use init when defining a class in Python. However, I am confused by what needs to be entered inside the init function, or if I will use it at all. For instance:

Here I define the user concept when instantiating a class:

class Fruit(object):
    def __init__(self, concept):
        self.concept = concept

But I could do this, and the user can simply change the attribute itself:

class Fruit(object):
    def __init__(self):
        self.concept = "I am a fruit"

Or I could just completely abandon the init function :

class Fruit(object):
    concept = "I am a fruit"

In each of these examples, I can change the attribute of the concept as such

test = Fruit()
test.concept = 'Whatever I want'

Therefore, I am not sure why I use the init function in the first place. It seems to be convenient only for defining all attributes in front.

, , init init?

+4
2
class Fruit(object):
    def __init__(self, concept):
        self.concept = concept

- , , , . , , ( Python , , ).

:

class Fruit(object):
    def __init__(self, concept):
        self.concept = concept
        self._super_secret_key = get_secret_key(concept)

, , _super_secret_key ( , ), _, , .

, __init__ , (, ) . , __init__ python?.


class Fruit(object):
    def __init__(self):
        self.concept = "I am a fruit"

test = Fruit()
test.concept = 'Whatever I want'

. , concept ? (.. , Fruit), .


class Fruit(object):
    concept = "I am a fruit"

, concept , . , :

In [1]: class Fruit(object):
   ...:     concept = "I am a fruit"
   ...:     

In [2]: a = Fruit()

In [3]: a.concept
Out[3]: 'I am a fruit'

In [4]: Fruit.concept = "I am NOT a fruit"

In [5]: a.concept # a.concept has changed just by changing Fruit.concept
Out[5]: 'I am NOT a fruit'
+4

.

, .

class Fruit(object):
    def __init__(self, concept='I am a fruit'):
        self.concept = concept
0

Source: https://habr.com/ru/post/1668124/


All Articles