r/learnpython • • Oct 19 '26

I cant understand classes (nor self and __init__)

5 Upvotes

Hello if you wonder i switched from lua and luau to python. its going well i can make basically anything with native python libraries but i cannot understand what is a class, what does self mean what does __init__ mean. i recently understood what if __name__ == __main__ does but still i cannot understand classes. if you could give an example or explaining for me to understand i would be so grateful

r/learnpython • • Feb 17 '21

Please explain __init__ like ive never heard of programming before. Its just not making sense.

481 Upvotes

'''

class Student:

def __init__(self, name, major, gpa)

    self.name = name

    self.major = major

    self.gpa = gpa

student1 = Student("Bob", "Art", 3.0)

'''

Why do i need to use the init and self function? Do i have to make a new init for every single class?

Why cant i just make a regular function like

def Student(name, major, gpa) ??

r/learnpython • • Dec 11 '25

When should I implement __post_init__?

10 Upvotes

I'm having a hard time wrapping my head around when to use __post_init__ in general. I'm building some stuff using the @dataclass decorator, but I don't really see the point in __post_init__ if the init argument is already set to true, by default? Like at that point, what would the __post_init__ being doing that the __init__ hasn't already done? Like dataclass is going to do its own thing and also define its own repr as well, so I guess the same could be questionable for why define a __repr__ for a dataclass?

Maybe its just for customization purposes that both of those are optional. But at that point, what would be the point of a dataclass over a regular class. Like assume I do something like this

      @dataclass(init=False, repr=False)
      class Thing:
           def __init__(self):
               ...
           def __repr__(self):
               ...

      # what else is @dataclass doing if both of these I have to implement
      # ik there are more magic / dunder methods to each class,
      # is it making this type 'Thing' more operable with others that share those features?

I guess what I'm getting at is: What would the dataclass be doing for me that a regular class wouldn't?

Idk maybe that didn't make sense. I'm confused haha, maybe I just don't know. Maybe I'm using it wrong, that probably is the case lol. HALP!!! lol

r/learnpython • • Jun 09 '25

__init__.py - possibly a stupid question, but why..?

31 Upvotes

Obligatory caveat - complete newbie to Python - learning quickly.

I've got a python module supplied with a hardware device to use on a RaspberryPi - the instructions from the manufacturer involve setting up a venv and lots of complication, which I don't want to do as I'll be importing their module to my own existing code base. Their code comes in a directory (icm20948) with a __init__.py module and is called as normal by using [from icm20948 import ICM20948]

My understanding is that the presence of the __init__ makes Python treat the directory like a module, and I suppose I could rename the __init__ to icm20948.py and then call it the same way in my code.

What's the reason for the __init__ / directory structure, and is there an advantage in keeping it that way?

r/learnpython • • Sep 10 '21

I'm new and I feel like __init__ is pointless, please help

3 Upvotes

I'm very new to programming, I've only been actively programming for roughly 2 weeks and the entire time, I've found no reason anyone could possibly find a good reason to use the __init__ constructer. __init__ just seems like the more complicated way to do something.

Can someone please give me a reason why I would absolutely need the __init__ constructer, or would at least find it very useful?

I think I just don't understand it's use. But I've watched so many videos on __init__ and I feel like I most definitely understand it's uses and just can't understand why someone would use it. But I see so many people using __init__, so surely it's very useful.

r/learnpython • • Jan 07 '24

Whats the ruling on using __init__.py in 2024?

33 Upvotes

Every time I am having a module import problem, I come across someone mentioning init.py, only to be reminded by a (much later SO answer) that it's no longer needed in Python 3. I often don't know who to believe.

What's the final ruling the utility of init.py in 2024 greenfield projects (i.e. no legacy code)?

r/learnpython • • Oct 23 '25

dataclass or __init__ parameter list really big, and don't want to use kwargs

5 Upvotes

I'm sketching up a class, which the constructor takes a lot of args: and all it needs to do is copy them into members. So I figured I could do

cclass PerformanceSession:

    def __init__(self, 
                 printer_config_path, 
                 printengine_buffer_MB,
                 images_folder,
                 artifacts_folder,
                 width,
                 height,
                 image_gap,
                 clock_speed,
                 num_pccs,
                 num_threads,
                 num_hdcs,
                 print_duration,
                 print_PD_level,
                 print_full_level
                ):
        self.printer_config_path = printer_config_path
        self.printengine_buffer_MB = printengine_buffer_MB

or I could declare __init__ as taking **kwargs, and then just pull all the args out of the list and use setattr() to copy the values. But at that point I loose any duck-typing and visibility of the args, when someone wants to call the constructor. I am getting the feeling my class is better written as a class that accepts a "dataclass" object and then I can either store the dataclass as a structure, or continue with my daft idea of copying all the members into local class members using setattr, or even use getattr() to magic the attributes.

I know this is very context dependant, and perhaps this thread is just me bouncing a ball around so OI can think it through aloud in my head. I just want to get away from long argument lists, if I was writing this in C++ or C# I would just declare a struct in a heartbeat, and pass that around. But Python is much more malleable, and wants to be more brief almost? Thoughts on **kwargs and usability or other?

/edit struggling with codeblocks (took me 5 attempts, yay for markdown) /edit supporting threads https://stackoverflow.com/questions/8187082/how-can-you-set-class-attributes-from-variable-arguments-kwargs-in-python https://www.reddit.com/r/learnpython/comments/lliwrf/using_arbitrary_argument_list_in_a_class/

r/learnpython • • Oct 29 '25

Creating __init__.py files. Any tips?

4 Upvotes

Note: I just started learn Python about weeks ago to get into Python. First on my own then I bought Mr. Matthes' book - Python Crash course and I'm getting to point where you do the projects so I am going set a project directory structure with sub-directories for src, modules, classes, etc. But research online shows I need to those files at each directory so the code there knows where the other resources are. Thanks for any help.

r/learnpython • • Mar 10 '18

Can someone ELI5 what def __init__(self) means? I still don't get it :\

131 Upvotes

https://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do

Stack has a question just like this... But the explanations are insanely verbose and complex. I legit don't understand a word they're saying:

... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically...

Just... What? The instance of the object? I don't understand what this means.

The init method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the init method

Again, don't understand. I don't know what a constructor is. But even if I did, I don't understand why it is passing the parameter to the init method.

Can anyone help elucidate what is going on?

r/learnpython • • May 29 '19

why do we use __init__??

199 Upvotes

when defining a class what is the difference between using __init__ and not using __init__ in a class?

r/learnpython • • Aug 30 '24

what can I put in __init__.py to make them useful

93 Upvotes

I recently learned (thanks wholly to others on this sub) how to organize my previously monolithic single .py file projects into modular directories (using poetry to make the project a package). I've been going at it all day, and this new world is very liberating and exciting!

But, now I have a bunch of empty __init__.py files in my project. Can I do anything useful with them? Do they work anything like class init, like 'execute everything in here first' when calling anything inside the same dir?

what can they be used for besides letting python know its a package structure?

r/learnpython • • May 12 '26

Why can't I use a return statement in an __init__ function?

20 Upvotes

Apologies if this has been asked before, but here's my code:

You can print in both (i.e. the check's), but I'm a little confused why this __str__ is specifically used, only so you can include a return statement. Is this just to simplify the __init__ & make sure it's only used for creating variables?

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade
        print("check 1")
        
    def __str__(self):
        print("check 2")
        return f"{self.name} {self.grade}"


joe_init = Student("joe", "A-")
print(joe_init.name, joe_init.grade)
print(joe_init)

r/learnpython • • Apr 11 '22

When to use methods in a class and when to calculate things in the def __init__()

84 Upvotes

Hi I'm hoping someone more experienced cares to offer their opinion. I have a class with the normal def __init__() but I'm finding that the calculated variables that I need are really simple. For example I need to multiply two numbers together, or divide two numbers. Would it be worth writing methods in the class (better for writing unit tests?) or should I stick to just doing the calculation within the def __init__() ? at the moment my def __init__ is a long list of self.x = x, self.y = y, self.new_variable = x / y, etc. What's the best practice?

Thanks.

r/learnpython • • Jan 16 '20

usefull example of __init__

137 Upvotes

hey I try do understand classes. Im on the constructor part right know.

Can you give me a usefull example why to use __init__ or other constructors ?

so far I find in all tutorials only examples to set variables to the class,

I understand how to do this, but not what the benefits are

like in the code below

class CH5:

    ''' Blueprint CH5 Transportsub '''

    def __init__(self, engine, fuel):
        self.engine= engine
        self.fuel= fuel

r/learnpython • • Jul 06 '20

What's an __init__() method and why we need it?

28 Upvotes

Am new to python. Will appreciate if someone can explain in a very basic way with example, what and why we need an init () method? What will happen if we don't use one?

r/learnpython • • Aug 13 '23

Why is using self and __init__ important?

51 Upvotes

I've been learning TKinter to create an interface with Python. Most of the examples I see online use self and __init__ while using Tkinter. I've never used __init__ or self before but it seems almost like it's necessary seeing most TKinter examples use it. I've watched some video's about it but still things are quite unclear. How does using self and the __init__ function help when creating a TKinter interface?

I've built an interface with Self and __init__ and without, but havn't run into any reason as to why I should prefer using it.

This is the code I've created following some examples:

But it frustrates me not knowing why I'm actually using __init__(self) and super().init__(). I havn't ran into a scenario yet where I realised why it's useful and how it helps me. That's why I feel like I don't understand it yet. Hopefully someone could help me with this.

import tkinter as tk
from tkinter import ttk
class App(tk.Tk): def init(self): super().init()
    self.geometry("300x190")
    
    #Create grid
    for cel in range(7):
        self.columnconfigure(cel, weight=1)
        self.rowconfigure(cel, weight=1)

    # Add widgets
    # Home page
    self.Homebutton = tk.Button(self, text= "Homebutton", command=lambda: self.HomeFrame.tkraise())
    self.Homebutton.grid(column=0, row=0, sticky ='nswe')
    self.HomeFrame = ttk.Frame(self)
    self.HomeFrame.grid(column=1, row= 0, sticky='nswe', rowspan = 7, columnspan=6)
    self.HomeLabel = ttk.Label(self.HomeFrame, text="Home")
    self.HomeLabel.grid(column=0, row=0, sticky='nswe')
    
    # page 2
    self.Frame2Button = tk.Button(self, text="Frame 2", command=lambda: self.Frame2.tkraise())
    self.Frame2Button.grid(column=0, row=1, sticky ='nswe')
    self.Frame2 = ttk.Frame(self)
    self.Frame2.grid(column=1, row= 0, sticky='nswe', rowspan = 7, columnspan=6)
    self.Frame2Label = ttk.Label(self.Frame2, text="Frame 2")
    self.Frame2Label.grid(column=0, row=0, sticky='nswe')
app = App() app.mainloop()

Edit: For anyone still struggling with this. I found a video that refactors a tkinter project without classes to a project with classes. This video cleared up a lot for me. https://www.youtube.com/watch?v=eaxPK9VIkFM

r/learnpython • • Oct 07 '21

Are there any other magic file names in a package other than __init__.py and __main__.py?

98 Upvotes

I can’t seem to find a comprehensive list of special dunder file names in a Python package. Perhaps I’m using the wrong search terms.

r/learnpython • • Jun 09 '26

Reload other class from init

6 Upvotes

I'm having problems with old code being cached and old errors being thrown, even though I've already fixed them, so I'm using reload to reload all classes that are imported later. Both files are in the same folder.

This works:

from classb import ClassB
from importlib import reload
import classb as classb
reload(classb)

class ClassA(): #classa.py
    def __init__(self,doreload):
        #Some other code

class ClassB(): #classb.py
    def __init__(self):
        #Do something

However, I want to use doreload to decide if ClassB should be reloaded, so I tried to move the code to __init__:

from classb import ClassB

class ClassA(): #classa.py
    def __init__(self,doreload):
        from importlib import reload
        import classb as classb
        reload(classb)
        #Some other code

This throws an error at the reload line:

ModuleNotFoundError: spec not found for the module 'classb'

I already tried to keep import reload outside the class and also used reload(ClassB) instead but that threw another error:

ImportError: module ClassB not in sys.modules

How do I reload another class from within __init__?

Edit: The problem is simply the app I have to use to test my code: It caches old code at unexpected times (at least when I don't expect it) and without using reload I'd have to restart the app pretty much every 5 minutes while testing, which is quite annoying. Reloading itself seems to be working fine.

r/learnpython • • Jul 10 '22

__init__ method

15 Upvotes

can some explain how does the __innit__ method works?

P.S: pls try to make the explanation as simple as possible.

r/learnpython • • Dec 06 '21

Question... Why always use __init__ and self?

18 Upvotes

So I'm struggling to see the advantage of using these. I'm just starting to learn python, made a basic command prompt RPG style game... Working on moving over to tkinter to add some graphics, and everything I see when I google something people are always using __init__ and self. I kinda understand how these work, but I'm just failing to see the advantage of using it over just passing values between functions (with function(value) or just making the object global if it's being used a lot). Is this just a format thing that's become the norm or is there an actual reason?

r/learnpython • • Jul 10 '23

Why have empty __init__.py files?

0 Upvotes

I've been looking into some projects for some opensource software i use and noticed a few of them have empty __init__.py files (for example https://github.com/netbox-community/netbox/blob/develop/netbox/core/__init__.py)

Whats the point of these?

r/learnpython • • Sep 15 '23

How should I be testing the __init__ of my class?

3 Upvotes

I'm building a wrapper for an API and I'm in the process of building my unit tests.

One thing I'm unclear on is how I should be approaching the testing of my class's __init__ method?

Given that the attribute's of my class are derived from a JSON API response, should I my class's attribute types?

r/learnpython • • May 29 '24

Do you use the '-> None' in the __init__?

11 Upvotes

Hi y'all,

I'm pretty new to all this, so I just saw this for the first time:

class Example:
def __init__(self, value: int) -> None:
self.value = value

I didn't know what the '-> None' was about, but it looks like it's just an indicator that the __init__ doesn't return anything. But doesn't __init__ usually not return anything? Do you guys use the '-> None' portion or no?

r/learnpython • • Jul 18 '21

How do I pass __init__ arguments to a subclass without repeating them?

124 Upvotes
class Modifier:

    def __init__(self, value, name):
        self.value = value
        self.name = name
        self.hidden = "yes"
        self.generate_add_modifiers = "{produces}"

    def generate_script(self):
        script = f"""{{
            #value = {self.value}
            #name = {self.name}
            hidden = {self.hidden}
            generate_add_modifiers = {self.generate_add_modifiers}
        }}"""
        return script


class DerivedModifier(Modifier):
    def __init__(self, is_positive):
        self.is_positive = is_positive

The above code is part of a game scripting language generator I'm working on. I've not dealt much with classes, but I assumed that arguments from a parents init method would get passed to it's childs init automatically.

However, pycharm is complaining about invalid arguments when I try to do the following:

m = DerivedModifier(name = Test, value = "50", is_positive = "True")

Is this not the case? How can I achieve this without repeating myself?

r/learnpython • • Jan 08 '24

I think I figured out how super and __init__ works (took a few days!)

7 Upvotes

Some questions and answers I think I figured out finally, please correct me where i'm wrong. I finally feel like i'm getting a good grasp on it now, thanks to various users here. Maybe this will help someone else.

Would love to hear feedback if my mental musings/learnings and assumptions are somewhat correct.

Q: Why do i need to use super() on a parents attribute when i define new arguments for a child class __init__, whereas when i do not redefine the __init__ i can access all the parents attributes fine.

A: Because a new init​​ method is written for the child, and any method thathas the same name as the parent method overwrites it. So if you want any code that is written in the parent init method to run, you need to call the parent init method with super (in the olden days you would call it explicitly) inside of your new defined method for the child class.If you do not create a new init​ method for the Child class, you do not need to use super and can access the parent's attributes just fine.

I am guessing you could also access them fine if the code in question in the parent class you relied on was written outside of the init method in parent (but that is usually considered not best practice). But the same concept remains, __init__ is just another method and you can run any method you like in the __init__ or use super() with any method in that __init__.

Q: Why do we still need to add the Parent arguments to the Child def init when we use those arguments in the super() call anyway?

A: You don't need to, you can run the parent init by using super as long as you provide the right arguments to it (either passed from the args defined for the child class, or assigned from an attribute in the child class, or by directly passing a string e.g. super().__init__("test"). The reason why you add the argument to the def init​​ in the child class is so you can extend or use the parent method, or do something with it.

But your parent class init could have only self as an argument, and you could do super().__init__Parent() to execute the initialiser.It would have been nicer if the Child class would have inherited those attributes if they are included in the arg definition of the child__init__ def and Python would have just assumed they are inherited from the parent. Or even include them despite creating a new __init__ inthe Child Class. I guess that can be done by assigning the parent attributes outside of the __init__ method, as then you would not be overwriting the init method, but i hear that is not best practice.

I was stuck with below question one a long time before i realised all the code in __init is run, i'm just adding it here anyone else gets stuck on this. I thought super() had to be run on every attribute in the parent class 🙂 which is why i couldn't wrap my head around it, seemed..redundant!

Q: But isn't it easier to just redefine the variables in the child class rather then calling super on every attribute you defined in the parent?

A: You are not calling super on every parent attribute, it only works on methods and you are calling the init method, so all code therein is run once you call it.

Q: Can i call super() any time?

A: Yes, you don't need matching arguments in the Child def init (that match the parent Class) as long you are providing the right parameters to the method (see above).

Q: When do you define a new def __init in a child class ?

A: Only when you want to redefine the input (e.g. the args to the Child class call (from Parent Class(make, model) to Child(year). If you want to keep the parents arg you do not need to define a new init, it will be passed on to the child. But if you do create a new one and you want touse the parent argument, be sure to include it, as you overwrite the parent init method.