-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).

4
  • 2
    self refers the current object. Commented Jul 5, 2015 at 7:39
  • docs.python.org/3/tutorial/classes.html. Note that, as it's missing a colon, your code won't work anyway. Commented Jul 5, 2015 at 7:43
  • But if I didn't create jason, I wouldn't have an object. What would self refer to at that point? Commented Jul 5, 2015 at 7:43
  • 1
    @ArdaBoğa if you didn't create jason you wouldn't be calling Enemy.__init__, so it wouldn't matter! Declaring a method is just like declaring a function - you define the parameters now that will get passed to it later on. Commented Jul 5, 2015 at 7:44

1 Answer 1

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__?

Sign up to request clarification or add additional context in comments.

2 Comments

__new__ is not a static method, it's a class method
Thank you for all the responses! I now understand that "self" refers to the object to be created in the program.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.