-7

I have two questions regarding this piece of code:

class Enemy
    def __init__ (self, x):
         self.energy=x

jason=Enemy(5)     
  1. Why do I have to use self when I create functions and instance variables? What is the purpose of using it?

  2. When we create the jason object, we assign it a life of 5, as Enemy(5). However, can class names take variables inside? Or is it the __init__ function which makes it possible? (I'd expect something like, class Enemy (x), when we declare the class).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Arda Boğa
  • 49
  • 8

1 Answers1

0

In python, for class methods, the first argument (which normally people name self) refers to the instance (object) of the class which was used to call the function, It does not have to be named self, but thats the convention.

Example -

>>> class CA:
...     def __init__(someotherself, i):
...             print(someotherself)
...             print(i)
...             someotherself.i = i
...
>>> CA(1)
<__main__.CA object at 0x00514A90>
1
<__main__.CA object at 0x00514A90>

When you do something like -

self.energy=x

You are setting the energy variable inside self (which denotes your current object) to x.

When you do -

jason=Enemy(5)

Python internally calls the __init__() method of Enemy with the values for x as 5 (and self as the current object). __init__() is called after object has been created by __new__() method, which is a class method, An SO question to help understand how new and init work - Python's use of __new__ and __init__?

Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176