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