r/learnpython • • Feb 20 '21

What are you having difficulty learning or are currently struggling to learn?

I'm curious what the community here has difficulty with when it comes to learning Python. Partly because I want to see if the more experienced community here (or myself) can help point you into the right direction. . . but also because I'm trying to come up with video tutorial ideas for future content and would love to hear from Python learners what would be most useful to dedicate our time on.

I'm looking forward to hearing what you guys have to say!

417 Upvotes

324 comments sorted by

View all comments

51

u/solitarium Feb 20 '21

Self just hasn’t clicked for me yet...

56

u/sje46 Feb 20 '21

I think what made it click for me was changing the word "self". "self" is arbitrary. It's convention, and you should definitely follow it. But it's not a special keyword or anything.

So if you have this:

class Planet:
    def __init__(self, name):
        self.name = name
    def transmit(self):
        print("Hello universe, this is the planet {}, is there anyone out there?".format(self.name))

ourplanet = Planet("Earth")
outplanet.transmit()

And change it to THIS:

class Planet:
    def __init__(banana, name):
        banana.name = name
    def transmit(myself):
        print("Hello universe, this is the planet {}, is there anyone out there?".format(myself.name))

ourplanet = Planet("Earth")
outplanet.transmit()

You can see that in the __init__ method, I changed it to the name "banana"...completely arbitrary. Change it to gorilla if you want. IT's just saying in this method, we will refer to the object itself as "banana".

The transmit method makes more sense, because we're using "myself". In this method, we will refer to the object itself as "myself". The Planet object is referencing its own name, which we refer to as "myself.name".

"self" is absolutely nothing special as a variable. You can even change the name you use between functions...it literally doesn't matter. It's just an argument that pops up automatically in an object when you call a method.

I hope I didn't confuse you, but it's easier to learn by doing than reading. Just change the name of "self" for methods, and then hopefully it will stick out very clearly to you what it's doing.

And if you're confused about __init__...that's a method that's automatically called when you create an object. Everything after hte first argument (the "self") is whatever you passed into the call, here, it would be "Earth". so "self.name = name" is essentially storing the name into the object itself for future use in other methods. It's just a storage system. We store "banana.name" and later on refer to it as "myself.name". Using multiple names for the object itself is confusing, so it's conventional to just use "self" all the time, like in the first example. But yeah, try renaming self in your programs, store arbitrary values, and call them in other methods. As soon as you got this down, you basically understand objects imo.

4

u/gd_choices_43 Feb 21 '21

Wow I just played around with your explanation and it totally just clicked for me! Thank you so much for this!! 🙌👀🙏🏻

23

u/Nythious Feb 20 '21

Self took a LONG time for me! It was forever until I realized self referred to an instance of a class and not the class. I'm gonna jot this one down to go over in the future.

15

u/Username_RANDINT def get_random_int(): return "RANDINT" # TODO Feb 20 '21

Here's a quick demonstration:

>>> class Foo:
...   def __init__(self):
...     print(self)
... 
>>> f = Foo()
<__main__.Foo object at 0x7fdf79221710>
>>> f
<__main__.Foo object at 0x7fdf79221710>

I think this often overlooked when trying to explain it.

5

u/forkheadbox Feb 20 '21

the first <__main...> is from the print statement right?

6

u/Username_RANDINT def get_random_int(): return "RANDINT" # TODO Feb 20 '21

Yes, __init__() is called when you initialise the class.

1

u/RaidZ3ro Feb 21 '21

No, it's because Foo is created in the 'main' script(file/module), so when the object is represented it's parent is "main".

2

u/solitarium Feb 20 '21

0.0 Ohhhhhhhhhhh!

10

u/groovitude Feb 20 '21

Every time you create a new object, you run the __init__() method to create a new instance of the class, but you're not completely rebuilding everything. In more concrete terms, if you have a class Dog with a method bark(), you don't have forty copies of the bark() method if you have forty Dog instances. You have one copy of the bark() method on the Dog class, which the forty instances all reference.

So when you do this:

>>> fido = Dog()
>>> fido.bark()

That's a more readable version of what's actually going on under the hood:

>>> fido = Dog()
>>> Dog.bark(fido)  # try it with a class of your own!

That's where you get self -- the instance is passing itself as a parameter to a method stored in the class.

3

u/MaraudingAvenger Feb 21 '21

I like this explanation a lot! -- pointing out that all the instructions for how an object behaves are stored in the class definition.

4

u/pedrocora Feb 20 '21

Self only clicked to me when I saw a video about classes on techwithtim yt channel. He spoke about self and bum, I got it once and for all.

4

u/MaraudingAvenger Feb 20 '21

So -- the best description of why we use self inside classes in python, to me, is to think of the method as a function outside of the class. Some examples first -- I used typing just to make things a little more explicit:

class Bloop():
    def __init__(self) -> None:
        self.blop = 5

    def show_blop(self) -> None:
        print( f'blop is {self.blop}' )

b = Bloop()
b.show_blop() #gets that 'b' (self) passed implicitly

so there we have an object called a Bloop, and when we make one of them, the thing we make has a blop with a value of 5 inside it.

I'm specifically interested in the show_blop() function in there. It takes self as a parameter, then accesses self.blop to print out the blop inside self.

What if that function was outside the class? How would it be written? The answer is almost exactly the same way:

class Bloop():
    def __init__(self):
        self.blop = 5

def show_blop(thing: Bloop) -> None:
    print( f'blop is {thing.blop}' )

b = Bloop()
show_blop(b) #gets a Bloop passed explicitly

in order for the function to work on a thing this is basically a design decision at its core; functions that work on class members are written the same inside and outside the class. self just represents the object that we're doing something to. The tricky thing is that class methods are all required to have self as the first argument, even if you don't use any members or methods from self in the function.

3

u/unphamiliarterritory Feb 20 '21

What is the "-> None" stuff, I haven't seen that syntax before?

2

u/MaraudingAvenger Feb 20 '21

it's the python version of typing -- in the line

def show_blop(thing: Bloop) -> None:

thing: Bloop means the function takes a thing of type Bloop. the -> None before the end colon means the function doesn't return anything (None). It's a slightly more explicit way of programming. If you're interested, check out the typing library. It's got lots of example code.

2

u/unphamiliarterritory Feb 20 '21

When you say "of type Bloop" you mean an object Bloop previously defined with the class keyword, right?

Thanks for the info on the typing library!

1

u/MaraudingAvenger Feb 20 '21

Yep! when you make a class, you're defining a new type of thing, like a string or an int -- and every one of the Bloops I create has a type of Bloop (or really, it'll be a __main__.Bloop, but that could be splitting hairs).

2

u/AchillesDev Feb 20 '21

To be more precise, the 'python version of typing' is better (and officially) called type hinting. It's there for people reading the code, but isn't enforced by the runtime.

2

u/Raknarg Feb 21 '21

*and static analyzers like mypy or Pycharm's built in version, which one should always be using with python

1

u/Acceptable_Dark_9340 Feb 21 '21 edited Feb 21 '21

class Pet: def init(self,name,claw): self.name = name

def walk(self):
    print(f"{self.name} walk without making any sound")

cat = Pet("Tom")

now call the method by class name(Pet) but this will

ask that you are required to pass a parameter which is

self

Pet.walk()

this will not work as the self parameter is empty

Pet.walk(self=cat)

""" cat is the object that I have created and passed as self. Now it will refer to the object and can call the function. You might have more than one objects. In that case, you might not need the function for every object. So, self is the object/instance it(self)."""

Pet.walk(self=cat) is as same as cat.walk()

Please look at the piece of code below and see what

self refers to

class Pet: def init(self,name): self.name = name

def walk(self):
    print(f"{self.name} walks without making any sound")

cat = Pet("Tom")

both of them below are the same

Pet.walk(self=cat) cat.walk()

Sorry for the language constraint. I don't know if my explanation would help you, though I have tried to contribute.

1

u/Raknarg Feb 21 '21 edited Feb 21 '21

If I have this class:

class Foo:
    def bar(x, y):
        ...

bar is a function of Foo. I could call Foo.bar(1, 2) if I wanted. However, if I have an instance of foo and call it:

foo = Foo()
foo.bar(2)

The way python works is that foo will be passed as the first argument of bar, so its actually like if I did this:

Foo.bar(foo, 2)

So the first parameter could be called anything, but since 99% of the time we're calling these functions from instance objects, semantically the first argument of a class method is almost always the object being referenced, so we call it "self" to indicate that the first variable is going to be the object of this class that's going to call this function. However the fact that it's called "self" is actually not special at all, it's just a common idiom.

1

u/[deleted] Feb 21 '21

Not to pile on because it looks like you're getting a ton of other answers, but self is referring to a future instance of the class. So when writing the class it might be a little confusing because when you're writing methods, those methods are only going to be called later once an instance of that class has been created.

1

u/RaidZ3ro Feb 21 '21

Self is just a way to say, "this object".

Use it to define an object's methods and properties (and to work with the current object in them).

Compare to Other.