1

Why do I need to write self in this code despite it works?

But with my instructor, it didn't work and gave him an error mean that function doesn't take a parameter and you gave it one it happened when he took an object and he solved the error my placing self as an argument in open_door() and close_door() functions but the error didn't happen to me

class ferrari_2018():
   color='red'
   def open_door():
      print('open door')
   def close_door():
      print('close door')

x=ferrari_2018
x.open_door()
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 2
    This code here has multiple problems, like you never calling the constructor, and having bad indentation. Please fix it so we know what code we're actually talking about. – Carcigenicate Nov 26 '19 at 20:25
  • 2
    Actually, the former is your problem. `x=ferrari_2018` should be `x=ferrari_2018()`. – Carcigenicate Nov 26 '19 at 20:29
  • You should read this, it will answer your question: https://stackoverflow.com/a/26789355/2241241 – fbence Nov 27 '19 at 00:28

1 Answers1

0
color='red'

creates a class variable named color, so this variable is shared by all instances of the class Ferrari_2018.

With this code, you can't have 2 Ferraris with differents colors.

I imagine that you want to affect a custom color to each car. So you need an instance variable, not a class variable :

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

With that, you can write :

x1 = Ferrari_2018('blue')
x2 = Ferrari_2018('yellow')

where x1 has its own attribute color (which is blue), and x2 has its own also.

Jacquelin Ch
  • 166
  • 5