0

where is a difference between creating a variable in a class and assign it a value in __init__ and creating the variable directly in __init__?

For example:

Example 1:

# I create the var color outside __init__ and assigns a value to it inside __init__

class Car:
   color = ""
   def __init__(self):
      self.color = "green"

Example 2:

# I directly create the variable inside __init__ and not outside __init__ and just assign a value in __init__

class Car:
    def __init__(self, color):
        self.color = color

Does it make a difference?

roganjosh
  • 12,594
  • 4
  • 29
  • 46
Salvatore
  • 99
  • 2
  • 5

2 Answers2

1

The first example has two different color attributes: color = "" creates a class attribute show value will be used if the instance doesn't have its own. self.color = "green" explicitly creates an instance attribute with the value "green".

In your second example, there is no class attribute, and you define the instance attribute using an argument to __init__ rather than a hard-coded value.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

__init__ is the constructor used to initiate an object when the object is created.

-> __init__(self): self.color='green'

this will create a class variable, and you won't be able to pass a new value while creating the object.

->__init__(self,color): self.color=color

On the other hand, above piece of code will allow you to assign color attribute to your object.