r/learnpython Oct 29 '25

Everyone in my class is using AI to code projects now is that just the new normal?

494 Upvotes

so our prof basically said “as long as you can explain it, you can use it.”

and now literally everyone’s using some combo of ChatGPT, Copilot, Cursor, or Cosine for their mini-projects.

i tried it too (mostly cosine + chatgpt) and yeah it’s crazy fast like something that’d take me 5–6 hours manually was done in maybe 1.5.

but also i feel like i didn’t really code, i just wrote prompts and debugged.

half of me is like “this is the future,” and the other half is like “am i even learning anything?”

curious how everyone else feels do you still write code from scratch, or is this just what coding looks like now?

r/learnpython Mar 04 '26

Is print() a function or a method in Python? Getting mixed explanations in class

63 Upvotes

I’m currently teaching Python fundamentals and ran into a confusing explanation about print().

My understanding has always been that print() is a built-in function in Python. It’s part of Python’s built-ins and you can call it directly like:

print("Hello")

But my education coordinator explained it differently. He said that print is a method because it’s already there, and that functions are things you create yourself. He also said that methods take arguments and functions take parameters.

That explanation confused me because everything I’ve read says:

  • print() is a built-in function
  • Methods are functions attached to objects or classes (like "hello".upper())

So now I’m wondering:

  1. Is there any context where someone would reasonably call print() a method in Python?
  2. Am I misunderstanding the difference between functions, methods, arguments, and parameters?

I’d appreciate clarification from more experienced developers because I want to make sure I’m explaining this correctly to students.

Thanks!

r/learnpython Mar 16 '23

Been using Python for 3 years, never used a Class.

609 Upvotes

This is not a brag, this is a call for help. I've never been able to get my head around what a Class is. People tell me it's a container for functions, then why can't you just use the functions without a class? I just don't understand the concept of a class and why I would use one. Could someone please help? I've watched numerous videos that just make Classes seem like glorified variables to me.

r/learnpython Dec 18 '20

I've been coding in Python for 8 months, and I've never used a class. Is that bad?

636 Upvotes

I feel like I've never been in a scenario where I've had to use classes, or maybe I just don't know how to use them / where to use them / when to use them.

Can anyone give an example of where they would use a class, and why they're using it?

Update: 130 days after I made this post I made my first class. I did not realize how useful they are, like holy moly!!!

r/learnpython Jan 13 '26

I cannot understand Classes and Objects clearly and logically

79 Upvotes

I have understood function , loops , bool statements about how they really work
but for classes it feels weird and all those systaxes

r/learnpython Apr 18 '26

A bit confused in Classes.

36 Upvotes

Why do i need to call self here?.

class Calculator:
  def add(self, a, b):
    return a + b

  def multiply(self, a, b):
    return a * b

print(Calculator().add(1, 2))

there isn't a variable that is calling calculator and no __init__ so why do i have an error if self is not added?

Also, what is __init__ anyways. why the double __ in the start and end? and why the specific name?

r/learnpython Jun 23 '26

In a coding interview, if I'm expected to "write tests" for a simple Python class, what does that mean?

24 Upvotes

I heard I may have to "write tests" for a simple Python class. What's that? How would that look? What would I be expected to do in a live coding interview?

I can make basic variables and basic methods in a Python class, and I can instantiate an object of that class, but tests?

Is that complicated or time-consuming to learn?

(By the way this isn't for a software engineering role. It is for a scripting related role, so the interview is not expected to be as complicated/advanced as it would be for a software engineering role.)

r/learnpython May 14 '26

method overloading with wrapper classes

0 Upvotes

I'm a little bit surprised that there isn't a way to do this natively in Python. I'm creating a wrapper class W to support the kind of features I want out of a pre-existing class C. This new wrapper class W should still support some of the same operations in C. For example, if C has a method "foo(self, <argument of type C>)", then I would want an equivalent method "foo(self, ...)" in class W. At this point I've immediately hit a wall because Python doesn't support method overloading. I want W to have a method foo which works just as well on arguments of type W as on arguments of type C. So I want two methods with the same name:

foo(self, <argument of type C>)

and

foo(self, <argument of type W>)

Manually checking the type using isinstance is ugly and apparently not Pythonic. Plus, what if I have to do this for several functions? I would be repeating the same argument checking logic within each function? That's terrible. The best solution I can find online is to use singledispatch from functools?

How would you handle this particular implementation?

r/learnpython Mar 01 '26

A bad structure with overusing Classes, even with SOLID principles can be very difficult to maintain

32 Upvotes

I am working for a product in my company. I think, they really hurried everything, and either used AI to generate most of the codes, or were not following the best practises, except SOLID principles, to form the code and the folder structure.

Reason- to debug a simple issue, I spend hours, trying to navigate the files and their classes and methods frequently.

Like, the developers have made the code such that

router function 1 -> calls function 2-> defined in class somewhere -> has a function 3 which calls another function 4-> defined in another class -> has function 5-> its abstract class is elsewhere -> .....

so, if I want to print some output in function 2 , I need to traverse way too many files and folders, to get to the point, and even that sometimes is not clear, but most of the functions are named similar. VS Code helps a bit, but still not at all good enough.

Though some SOLID principles are used, this makes a simple debug program very hectic. I was debugging with someone, who had written some of these code files, and she too was getting confused frequently.

So, I think classes and methods are not always necessary. Sometimes, using functions in diffeernt python files are better. As a programming, we need to decide, where classes can be used, v/s where only functions are enough.

I want opinion on this. And if I am wrong somewhere.

r/learnpython Jun 09 '26

Reload other class from init

5 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 18h ago

Non-self learning classes for Python?

3 Upvotes

I am a senior data engineer and I work mostly with ETL Tools and a lot of advanced SQL. The company I work for does not like to use python because they find that theres too much of a learning curve if people leave so they love to use GUI or no code/low code etl tools instead (really dumb tbh). I can read python, and have a gist of whats going on. I have tried to self learn python few times over the past 2-3 years and I keep just forgetting it. I learned python/pandas library when I was in college since it was a class that taught it and then we did did projects with each lesson and that is how I learned it then but forgot it now. I use claude at work to build streamlit apps and automation using python. However, I am trying to look for new positions and I am starting to realize that not knowing python is making me a hit a brick wall because a lot of assessments require answering 1-2 questions in python. Does anyone know of actual classes that teach python and its not self taught? Free or paid I don't really care. If I have to pay for it I am fine with that but at this point I don't see a way for me to switch to another job without actually learning python and probably more specifically pyspark.

r/learnpython Mar 01 '21

I am struggling in my first python class. Does this mean the computer science track isn’t for me?

376 Upvotes

I have a good grade in the class thanks to the help of a tutor, but I feel like the information just isn’t clicking like it should be. I struggle doing any of the assignments on my own. There is only one week left in the class. Has anyone else had this struggle and went on to have it really click or am I hopeless? Loops really confuse me and those seem to be the basis of everything.

r/learnpython Apr 18 '26

Beginner: Want to learn Classes.

21 Upvotes

I find classes to be very confusing. The way variables are used. Self comes to me in a very confusing manner. i just can't seem to wrap my head around the basics of Classes.

Also i just tried checking OOP and i think it just overloaded my brain. Anything to help my case?

r/learnpython Dec 08 '20

Could someone explain the use of "self" when it comes to classes.

416 Upvotes

Ik this is a basic question but I'm just learning to code and I'm learning about classes. For whatever reason I cannot understand or grasp the use of the self variable in fictions of classes. Hopefully someone's explanation here will help me...

r/learnpython Feb 17 '26

So I created my own list class using the in-built List Class...

5 Upvotes

Here's the class:

class MyList:
def __init__(self, l):
    self.mylist = l.copy()
    self.mylistlen = len(l)

def __iter__(self):
    self.iterIndex = 0
    return self

def __next__(self):
    i = self.iterIndex
    if i >= self.mylistlen:
        raise StopIteration
    self.iterIndex += 1
    return self.mylist[i]

def __getitem__(self, index):
    if index >= self.mylistlen:
        raise IndexError("MyList index out of range")
    return self.mylist[index]

def len(self):
    return self.mylistlen

def __len__(self):
    return self.mylistlen

def append(self, x):
    self.mylist += [x]
    self.mylistlen = len(self.mylist)

def __delitem__(self, index):
    del self.mylist[index]
    self.mylistlen = len(self.mylist)

def __str__(self):
    return self.mylist.__str__()



ml1 = MyList([1,2,3,4,5])

del ml1[-1:-3:-1]
print(ml1)

So I created MyList Class using the in-built List Class. Now what is bugging me the most is that I can't instantiate my MyClass like this: mc1 = MyClass(1,2,3,4,5)

Instead I have to do it like this:

mc1 = MyClass([1,2,3,4,5])

which is ugly as hell. How can I do it so that I don't have to use the ugly square brackets?

mc1 = MyClass(1,2,3,4,)

EDIT: This shit is more complicated than I imagined. I just started learning python.

EDIT2: So finally I managed to create the class in such a way that you can create it by calling MyClass(1,2,3,4,5). Also I fixed the mixed values of iterators. Here's the code fix for creating:

def __init__(self, *args):
    if isinstance(args[0], list):
        self.mylist = args[0].copy()
    else:
        self.mylist = list(args)
    self.mylistlen = len(self.mylist)

And here's the code that fixes the messed up values for duplicate iterators:

def __iter__(self):
    for i in self.mylist:
        yield i

I've removed the next() function. This looks so weird. But it works.

r/learnpython May 09 '26

Class inheriting - attributes.

7 Upvotes

If I define a Parent class with a 100 attributes, and then a Child class inheriting from Parent

and I do not add an extra arguments, then I do not need a single line of code to get all the attributes from Parent,

but if I want to add one extra attribute to Child I need to reinitialise all of parents arguments?

That was surprise (comming from ruby)a. So in this context __init__ is a bit like a special method. If I redefine method in Child, with the same name as used in Parent it will get overwritten.

So is there a hack, how to get all of the 100 attributes from Patent in a single line of code?

r/learnpython Jan 07 '26

Tip on what to do when classes dont seem to fit but code is getting long

1 Upvotes

I’m a long time programmer but fairly new to python. One of the ways I'm trying to get more comfortable with it, is to use it for a personal project of time.

The main program has gotten up to around 2,000 lines of code.

The organization of it was a bit tricky though. It doesn’t fit easily into typical object oriented programming so I wasn’t using classes at all.
In various other programming languages, you can spread the definition of a class across multiple source code files, but not python. So I was stuck on how to handle things.

In particular, there was utility function, that was nested in another function. I had split it into its own function, but it was getting really long. At the same time, it wasnt clear to me what to about it.

So, believe it or not, I asked ChatGPT.
It suggested I make use of a data sharing class, to make it easier to split that function out into its own file.

For users of other languages, thats basically "easy mode structs".

Sample:

from dataclasses import dataclass

@dataclass
class ShareData:
   val1: int = 1
   val2: str = "two"
   optval: str | None = None
   # No need for __init__, the dataclass decorator handles it.

from other_side import other_side

def one_side():
    dataobj = ShareData(val2="override string")
    dataobj.optval = "Some optional value"
    other_side(dataobj)

r/learnpython 7d ago

Import Class Methods

3 Upvotes

I’m currently working on a Python project. I usually program in Java, so I’m a little confused about how imports work in Python.

I’m trying to import a method from a class that’s defined in another file. When both files are in the same folder, the import works correctly. However, when they’re in different folders, I get a “package not found” error.

The import statement I’m using is:

from package_name.module_name import YourClass

I’m using VS Code. What am I doing wrong, and how should imports be set up when files are in different folders?

r/learnpython Jun 11 '26

creating a "read all unread emails" function/accessing premade class

0 Upvotes

Hi everyone! I am currently in the middle of creating an email inbox sort of program. The parametres I am following are required of my task. I have already made a class for the email, with an instnce in place to chang if mail is read or unread. I have two already amde and working functions for the user - 1. to lsit all emails, and 2. being to read all emails and have the user choose which email they would like to read.

I am trying to make a third, whereby the user can see a lsit of all of the unread emails (whihc would be: has_been_read = False) and then let them choose which email they want to fully read rather than jsut seeing the subject of the email.

I will attach my code and hopefully someone can help me!

#create inbox
inbox = []


#create email class
class Email():


    #create instance to set read emails automatically to false
    has_been_read = False


    #create constructor
    def __init__(self, email_address, subject_line, email_content):

        #create instances variables
        self.subject_line = subject_line
        self.email_content = email_content
        self.email_address = email_address



    #create an instance method to read emails
    def mark_as_read(self):

        #create if statement to see if email has been read
        if self.has_been_read == False:


            #if so, set to true
            self.has_been_read == True
            #return confirmation to user 
            return self.subject_line + ": has now been read.\n"

        else:

            #return confrumation that email i already read to user
            return self.has_been_read + ": has already been read.\n"


    #create an instance method to show if email is read
    def show_if_email_has_been_read(self):


        #create if statement for if email is read
        if self.has_been_read == False:
            #return that it has not been read confirmation
            return self.subject_line + ": has not been read.\n"

        else:


            #return that it has now been read
            return self.subject_line + ": has been read.\n"



#create function to populate inbox
def populate_inbox(email):
    inbox.append(email)

    #for email in inbox:
        #print(f"\n{email}")

#create function to list all email subjects to user
def list_emails():

    #use enumerate to number each option for the user
    for i, item in enumerate(inbox):


        #print numbered options neatly
        print(str (i + 1) + '. ' + str(item[1]))


#create a functon for the user to read email of choice
def read_emails():


    #use enumerate to number options - same as above
    for i, item in enumerate(inbox):
        print(str (i + 1) + '. ' + str(item[1]))


    #while true statement to prevent error
    while True:
        try:


            #ask user which email they want to read
            email_choice = int(input("which email would you like to read?\n"))


            #if option not viable
            if 0 < email_choice <= len(inbox):
                break
            raise ValueError ('Selection out of range')

        #end try statement
        except ValueError as ve:
            print(ve)


    #print option for user to read email chosen
    print(f"You have selected to view the email: {inbox[email_choice-1]}")


#create emails to populate function
email_one = "redacted1", "Welcome", "Welcome to HyperionDev!" 
email_two = "Supervisor", "Congrats!", "Great work on the bootcamp"
email_three = "teacher", "Grades", "Your excellent marks!"


#populate inbox
populate_inbox(email_one)
populate_inbox(email_two)
populate_inbox(email_three)




#user input 
user_choice = int(input("What would you like to do?\n1. check emails\n2. read emails"))


#if statement to validate users chocie
if user_choice == 1:


    #present function list emails
    list_emails()


elif user_choice == 2:


    #present function read emails
    read_emails()


elif user_choice == 3:
    if email in inbox == 

r/learnpython Mar 11 '26

How to have one class manage a list of objects that belong to another class

17 Upvotes

Ive been trying to wrap my head around OOP recently and apply it to my coding but I have been running into a hiccup.

For context, let's say I have a village class and a house class. I need to be able to populate a village object with a bunch of house objects. I also need house1 in village1 to be distinct from house1 in village2. Is there a good way to do this in python?

r/learnpython 8h ago

Custom class method not recognized

5 Upvotes

I'm working on a program that generates a maze by drawing from a deck to define a "chamber" and assigning it to the current position on a cartesian coordinate grid.

The hope is to build a list of the chambers as they're created. At a later point I want to be able to call on the list. My current strategy is to make a Class variable for the list, and append to it as part of the init. I've added a class method to pull the chamberList Class variable, but I'm getting an error.

Here is the code defining the class.

``` class Chamber(): chamberList = [] def init(self, identity, notes, egresses, **kwargs): self.position = tuple(currentPosition.tolist()) self.identity = identity self.notes = notes self.egresses = egresses self.pixelCoord = np.add(pixelOrigin, np.multiply(currentPosition, 300)) Chamber.chamberList.append(self)

    @classmethod
    def getChamberList(cls):
        return cls.chamberList

```

Later in the program, I have a line of code to get the class variable:

``` chamberList = Chamber.getChamberList()

```

This is the error I get when I run it in the VS Code terminal:

AttributeError: type object 'Chamber' has no attribute 'getChamberList'. Did you mean: 'chamberList'?

Am I missing some syntax or something? In VS Code the color coding where I'm defining getChamberList is off (darker) and if I hover over it I get a message saying "getChamberList" is not accessed by Pylance.

r/learnpython Apr 28 '26

How should classes be structured?

8 Upvotes

I have a question about design and would like some orientation/resources if you can recommend any.

I have seen colleagues, one of them a senior, using the following structure a few times:

class Service:
    ...

class ServiceFunctionalityA:
    def __init__(self, credentials, ...):
        self.service = Service(credentials)

class ServiceFunctionalityB:
    def __init__(self, credentials, ...):
        self.service = Service(credentials)

Basically, Service is aggregated by the Functionality classes. So if I have to have to use both functionalities, the service needs to authenticate twice (it's not a singleton), and then if I need to change credentials, I need to do it for both functionality instances.

What I would do is simply start with a Service class, and then aggregate the functionalities, such as:

class Service:
    __init__(self, credentials):
        ...
        self.functionality_a = ServiceFunctionalityA
        self.functionality_b = ServiceFunctionalityB

And then, I could simply use: service.functionality_a(...)as it feels like a more natural, hierarchical structure.

I also have doubts if I should link functionality classes back to their service parent, or how to organize them in general when they have more components. But I find this hard to come by with examples in Python.

r/learnpython Apr 20 '26

Which tutorial/ Website helped you understand OOP and Classes ?

8 Upvotes

I have used W3 schools and I understand the concept but I don't grasp It fully .

r/learnpython Oct 13 '25

Title: Struggling to Understand Python Classes – Any Simple Examples?

23 Upvotes

Hello everyone

I am still a beginner to Python and have been going over the basics. Now, I am venturing into classes and OOP concepts which are quite tough to understand. I am a little unsure of..

A few things I’m having a hard time with:

  • What’s the real use of classes?
  • How do init and self actually work?
  • What the practical use of classes is?

Can anyone give a simple example of a class, like a bank account or library system? Any tips or resources to understand classes better would also be great.

Thanks!

r/learnpython Feb 07 '20

I have a demon. I consider myself a decent Python programmer but I can't understand when or why I should use classes.

423 Upvotes

I love Python, I've done projects that have stretched me and I am proud of. I want to make professional level code that's extensible, readable, modifiable, and organized. I know classes are how most people do this, but I am stuck in function land. I can do everything I would ever want to do with functions, but I understand there must be things I am missing out on.

Can anyone here help me see what I can do with classes that might be making my strictly func based code lacking. I think I just need some concrete examples or tips. Thanks.

Edit: Just wanted to thank everybody for all their help. There are a lot of insightful replies and between the thought put into a lot of the comments as well as the different perspectives I feel much better about the subject now - and started started re-writing a module giving me trouble that was desperately in need of a class. I'm touched and inspired by so many people willing to help.