Methods

https://www.codecademy.com/courses/learn-python-3/lessons/data-types/exercises/methods
In the Methods exercise under Classes in Python 3 course, I do not understand what self is.

I have tried to understand by reading the community forums but I still do not understand. I can follow the instructions and get the answers correct but I still do not have an understanding. I do not even know what I don’t understand about it but I just do not understand self.

WHAT IS THE PURPOSE OF SELF IN THE FUNCTION AND WHY IS IT NECESSARY?

I think that I do not even understand classes as a whole. I do not mean the entire syllabus under Classes, just the idea of a “class”. Why do I need to create classes? WHAT IS THE PURPOSE? Can I have an example. I really want to understand. I just cannot move on until I have a full understanding or else I’ll just confuse myself even more.

Classes are usually considered part of the object-oriented programming paradigm (Object-oriented programming - Wikipedia).

It is a way to abstract code in a way that aims to be efficient. There are other paradigms that eschew classes all together.

self is the way you reference a particular instance of a class. If you have class Person it’s basically represents an outline for generic Person. Once you say: “make a new Person named Joe”: every time you call self.name on that new object it will return “Joe”.

A possible exercise to do is to do a simple coin-flip or dice game and have a 2 players (of class Player). Player can have a wallet and a name, so after every round you can check how their wallet is being changed.

2 Likes

Classes are a design pattern, a way to organize your code. And there is the problem, you first need to learn the basics of classes before you can reap the benefits. Classes start to shine once your application becomes larger.

Classes are not some kind of holy grail to solve all of the problems, classes have pros and cons just like everything else

self is the current instance of the class, we can do this with an example indeed:

class ExampleClass:
    def example_method(self):
        print('hello world')
        
        
example_instance = ExampleClass()
example_instance.example_method()
ExampleClass.example_method(example_instance)

self is a parameter, just like you have learned in function. Except when you call a method on class instance/object, python is taking care of the argument, as demonstrated here:

example_instance.example_method()

in the other method call:

ExampleClass.example_method(example_instance)

the argument (example_instance) matches with the parameter (self).

By having self as a parameter, we can access instance variable in methods.

3 Likes

Thank you. I understand a little bit better now but you lost me at the last part with the game. I’m still lost overall. Look at this code.

image

If self is referencing converter which is the instance, and the instance (converter) is referencing the DistanceConverter() and DistanceConverter() is referencing the everything after class DistanceConverter: located at the top of the code to return miles * self.kms_in_a_mile, then how is return miles * the few lines of code that follow class DistanceConverter: .kms_in_a_mile equal to 8.045.

Or…or in:
kms_in_5_miles = converter.how_many_miles(5)

If self is converter and converter is the instance then how does miles * self.converter which is actually DistanceConverter equal to 8.045.

I’m really trying my best to wrap my head around it, maybe I’m missing something? Any explanation is welcome at this point because I don’t even know what I am talking about.

I’m sorry I’m just not getting it. Take a look at my thought process and see if you can point me in the right direction.

image

If self is referencing converter which is the instance, and the instance (converter) is referencing the DistanceConverter() and DistanceConverter() is referencing the everything after class DistanceConverter: located at the top of the code to return miles * self.kms_in_a_mile, then how is return miles * the few lines of code that follow class DistanceConverter: .kms_in_a_mile equal to 8.045.

Or…or in:
kms_in_5_miles = converter.how_many_miles(5)

If self is converter and converter is the instance then how does miles * self.converter which is actually DistanceConverter equal to 8.045.

I’m really trying my best to wrap my head around it, maybe I’m missing something? Any explanation is welcome at this point because I don’t even know what I am talking about.

In my humble opinion, having the lesson use DistanceConverter as a class is maybe not optimal to highlighting the basics of classes.

I just wrote a little example you can play with:

class Animal:
	def __init__(self, name, message):
		self.name = name
		self.message = message

	def speak(self):
		print("The {} says {}!".format(self.name, self.message))

cat = Animal("cat", "meow")
dog = Animal("dog", "woof")
whale = Animal("whale", "uuuuuuuuoo")

cat.speak()
dog.speak()
whale.speak()

Output so far:

The cat says meow!
The dog says woof!
The whale says uuuuuuuuoo!

Self can be thought of as: “who am I?”

If you ask the dog who it is, (the dog will think, who am I?) it will tell you “dog”, cat will tell you “cat”… etc.

1 Like

Ohhhh! So self is just basically a space holder for the actual variable so that the programmer doesn’t have to write the code every single time. Am I correct?

It’s not necessarily a placeholder, it refers to the current object. Writing self allows our code to work for all instances of a class.

Example

class Person:
  def __init__(self, name);
    self.name = name

john = Person("John")
jane = Person("Jane")

print(john.name) # prints John
print(jane.name) # prints Jane

In the above example, for the object john, self refers to john. For the object jane, self refers to jane. Essentially, self refers to itself (the current object). By using self, our code works for any object of the Person class. For example, self can refer to both john or jane depending on which object you are referring to.

1 Like

Ok now I understand totally. Thank you very much @victoria_dr @toastedpitabread @stetim94
Now I can move on to the next topic with understanding!
:slight_smile:

3 Likes