r/learnpython • • Nov 02 '26

Ask Anything Monday - Weekly Thread

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

5 Upvotes

15 comments sorted by

View all comments

Show parent comment

1

u/lakseol Nov 02 '26 edited 29d ago

class is a group of similar functions,

And data, not just functions. When you call the class constructor you get a class instance which is what you normally use. So in this code Test is the class name and t1 and t2 are class instances (or just instances for short):

class Test:
    pass
    
t1 = Test()   # one instance
t2 = Test()   # another instance

why do we have to use self everytime at the class starting function

I assume by "starting function" you mean the __init__() method. Every method of a class (not just __init__()) needs the self parameter because that is a reference to the particular instance you are using in the method. Don't forget, you write the class methods before you call them and you might have created hundreds of instances. There's only one copy of the method code and the method needs to know which instance you want that method to operate on. In this sample code:

class Test:
    def __init__(self, name):
        self.name = name
        
    def greet(self):
        print(f"Hello {self.name}")    # note that we NEED 'self' to get the name for the instance
          
t1 = Test("Alice")
t2 = Test("Bob")
t1.greet()
t2.greet()

the greet() method call is t1.greet() which, under the hood, is actually doing something like this:

Test.greet(t1)    # note the instance reference is passed as the first argument

Note that the name self is just a convention. You are allowed to use any name you like for that first parameter to a method (try it) but self is expected and any other name is viewed with suspicion.

Edit: clarified the idea of there only being one copy of a method code.