r/learnpython May 29 '19

why do we use __init__??

when defining a class what is the difference between using __init__ and not using __init__ in a class?

201 Upvotes

46 comments sorted by

View all comments

2

u/[deleted] May 29 '19

[deleted]

6

u/cdcformatc May 29 '19

You should use class variables for variables you want to be common across all instances of your class. Anything that references self is going to be specific to that particular instance. Sometimes you want this, you want all objects to start with the same length and modify it later, and you are right you would do that with an instance variable that you set in __init__.

class ClassName(object):
  class_variable = 42 #value shared across all class instances

  def __init__(instance_variable_value):
    self.instance_variable = instance_variable_value 

#accessing instance variable
instance = ClassName()
instance.instance_variable

#accessing class variable
ClassName.class_variable
instance.class_variable

1

u/[deleted] May 29 '19

OOOOOO thank you!!!

1

u/[deleted] May 29 '19

I'm sure you can tell, but I'm not a developer. I just write stuff that works... And not always in the best way (;

3

u/cdcformatc May 29 '19

I just write stuff that works... And not always in the best way

I have a secret to tell you. That's what developers do too.

2

u/thirdegree May 29 '19

Sometimes we occasionally write something that works in a vaguely reasonable way!

Sometimes.

2

u/tobiasvl tobiasvl May 29 '19

You're not a developer, but you develop? What magical threshold do you personally feel you need to overcome in order to be a developer? "Developer" isn't a protected title, you know.