0

Have two simple python codes, both are working. But no sure what is the "self" in there that makes the difference. When to use and when not to use "self"?

class car:
 colour="red"
 def method1():
   print("method1")
myCar=car
myCar.method1()

class car:
 colour="red"
 def method1(self):
   print("method1")
myCar=car()
myCar.method1()
Meng
  • 3
  • 1

1 Answers1

0

In the first snippet, myCar refers to the class car, and method1 appears to be being used as a static method of that class.

In the second snippet, myCar refers to an instance of the class car, and method1 is an instance method -- the typical usage. Instance methods receive as a first argument the instance calling the method.

Conceptually, the difference is that in the second snippet you're referring to a car and in the first snippet you're referring to the concept of cars in general.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112