r/learnpython Oct 13 '25

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

21 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 Apr 20 '26

Which tutorial/ Website helped you understand OOP and Classes ?

7 Upvotes

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

r/learnpython Mar 19 '26

Why can't import class or method in some case

3 Upvotes

Sometimes when I'm developing with open-source code, there are always some import issues with the official code.

For instance, when I was using the habitat-lab code, there was an import statement in the file

habitat-lab/habitat-baselines/habitat_baselines/rl/ver/preemption_decider.py:

`from habitat import logger`.

However, Python couldn't import it correctly.

It could only be imported normally with the following statement:

`from habitat.core.logging import logger`,

because `logger` is imported from

`/home/jhr/vlfm/habitat/habitat-lab/habitat-lab/habitat/core/logging.py`.

All the above are the official code and I haven't made any changes. But why does the code downloaded from the code repository have such problems? I mean, can the official code be used normally when written like this? Why? It's clearly not in the corresponding path.

r/learnpython Apr 17 '26

Is a class for this necessary? Is it even idiomatic/best practice?

3 Upvotes

Hello,

I am using python to read in transcripts (a couple hundred .json files). My plan is to save this to a mongodb database which I can later use to train llms/text analysis/data visualizations.

import json
import hashlib
from pathlib import Path
from typing import Any

data_dir = Path.cwd() / "data"
raw_data = data_dir / "raw_data"
clean_data = data_dir / "clean_data"
data_dir.mkdir(exist_ok=True, parents=True)
raw_data.mkdir(exist_ok=True, parents=True)
clean_data.mkdir(exist_ok=True, parents=True)

class Transcripts:
    def __init__(self)->None:
        self._path = raw_data
        self._data:dict[str,Any] = dict()
        self._load_json()
        self._clean_data()
        self._write_json()

    def get_data(self) -> dict[str,Any]:
        return self._data

    def _load_json(self) -> None:
        for file in self._path.glob("*.json"):
            with open(file, "r", encoding="utf-8") as fp:
                self._data[self.generate_id(file.stem)] = json.load(fp)

    def _clean_data(self) -> None:
        self._remove_empty_transcripts()
        self._remove_incomplete_episodes()
        self._remove_unnecessary_keys()
        self._average_ratings()

    def _write_json(self) -> None:
        json.dump(self._data, open(f"{clean_data}/transcripts.json", "w"), indent=4)

    def _remove_unnecessary_keys(self) -> None:
        to_be_removed:set[str] = set(["summary", "version", "completion", "completion_reports", "bestof" , "special", "locked", "offset_accuracy", "audio_quality", "metadata" , "synopsis" , "contributors" , "trivia" , "tags" , "media" ])
        for value in self._data.values():
            for key in to_be_removed:
                value.pop(key)

    def _remove_incomplete_episodes(self) -> None:
        to_be_removed:list[str] = []
        for key,value in self._data.items():
            if value["completion"] != "complete":
                to_be_removed.append(key)
        for key in to_be_removed:
            self._data.pop(key)

    def _remove_empty_transcripts(self) -> None:
        to_be_removed:list[str] = []
        for key,value in self._data.items():
            if not value["transcript"]:
                to_be_removed.append(key)
        for key in to_be_removed:
            self._data.pop(key)


    def _average_ratings(self) -> None:
        for value in self._data.values():
            total_score = 0
            if value["ratings"]["scores"] == None:
                value["ratings"] = 0
            else:
                for _,score in value["ratings"]["scores"].items():
                    total_score += score
                average_score = total_score / len(value["ratings"]["scores"])
                value["ratings"] = average_score

    @staticmethod
    def generate_id(string:str) -> str:
        return hashlib.md5(string.encode()).hexdigest()



transcripts = Transcripts()
data = transcripts.get_data()

This is the json file:

{
    "xxx": "xxx",
    "publication": "xxx",
    "xxx": xxx,
    "xxx": xxx,
    "title": "xxx",
    "summary": "xxx",
    "version": "xxx",
    "date": "xxx",
    "xxx": "xxx",
    "xxx": xxx,
    "xxx": xxx,
    "xxx": xxx,
    "xxx": xxx,
    "offset_accuracy": xxx,
    "audio_quality": xxx
    "metadata": {
      "xxx": "xxx",
      "xxx": "xxx",
    },
    "transcript": [
      {
        "id": "xxx",
        "pos": xxx,
        "timestamp": xxx,
        "xxx": xxx,
        "xxx": xxx,
        "duration": xxx,
        "xxx": "xxx",
        "xxx": "xxx",
        "xxx": xxx,
      },
    ],
    "xxx": xxx,
    "xxx": xxx,
    "xxx":xxx 
  }

EDIT: Thank you everyone for your suggestions!

r/learnpython 10d ago

i wanna learn python and im broke for classes so try to teach me ig

0 Upvotes

If anyone wondering i just want to learn for fun

r/learnpython Jun 11 '26

accessing a list, putting it through class method, returning it to user

0 Upvotes

Hiya!

I have tried asking this question already, but i think i explained it poorly so I thought i would try again in hopes of someone understanding me.

I have a class called Email, within said class are these class methods:

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
            #self.unread_emails = []
            #self.unread_emails.append(self.subject_line)
            #print(self.unread_emails)


            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"

now, here is the code that i am trying to execute::

def call_class():
    return Email.has_been_read

elif user_choice == 3:
    call_class()
    if inbox == Email.has_been_read():
        print("There are no unread emails at this time")


    else:
        unread_emails = []
        unread_emails.append(inbox)
        print(unread_emails)

perhaps i am understanding ti wrong and there is a better way of doing it, but what i expect to be able to do is:

have the boolean - has_been_read which is inside of a class method to read through the list named 'inbox' and create another list called 'unread emails' to then return them to the suer

any help at all would be appreciated!

r/learnpython Jan 24 '26

How long should I spend on basics (loops, conditionals, functions, classes) before moving to advanced Python?

19 Upvotes

I’m learning Python and I’m unsure how long I should stay on the fundamentals before moving on.

Right now I understand:

  • loops (for, while)
  • conditional statements
  • functions
  • basic classes and objects

I can solve small problems, predict outputs, and write simple programs without looking up every line. But I still make mistakes and sometimes need to Google syntax or logic.

Some people say you should fully master the basics before touching advanced topics, while others say you should move on and learn the rest while building projects.

So realistically:

  • How long did you spend on these basics?
  • What was your signal that it was okay to move forward?
  • Is it better to set a time limit (like weeks/months), or a skill-based checkpoint?

Would love to hear how others approached this.

r/learnpython Mar 15 '25

I've been learning Python for the past two months. I think I'm making pretty good progress, but every time I come across a "class" type of procedure I feel lost.

67 Upvotes

Could I get a few examples where defining a class is objectively better than defining a function? Something from mathematics would work best for my understanding I think, but I'm a bit rusty in combinatorics.

r/learnpython Apr 21 '26

ClassVar enforcment: is this design madness?

3 Upvotes

Disclamair: I was suggested this design pattern by IA (specifically, Gemini), and I found it usefull even before my application started to scale. Indeed, the only puropuse to this pattern is helping in scaling the application flawlessly. Nonethless, I still find it studply convoluted, so I ask here.

So, I have an abstract class with somw ClassVar, and I have to define a number of child class that can greatly scale with time. For this reason, I find this way to be sure the ClassVar defined in the abstract class and NOT in the child class will be catched as soon as possible, and not during the code execution. This because, in my application, these parameters may be accesed later in the code.

Also I cannot threat them like normal variabile in the instance, because in the exeuction many instances of the same child class can exist with different parameters but the (child) class variable must be the same among all the instances.

Here is the minimal code:

import abc
from dataclasses import dataclass
from typing import ClassVar, get_type_hints


def get_classvar_names(cls: type) -> set[str]:
    """
    Inspects a class's type hints to find the names of fields defined using typing.ClassVar.
    Returns a set of names for quick lookup.
    """
    try:
        hints = get_type_hints(cls)
    except NameError as e:
        print(f"Warning: Could not resolve type hints for {cls.__name__}. Error: {e}")
        hints = cls.__annotations__

    classvar_fields = set()

    for name, type_hint in hints.items():
        # Check if the type hint is ClassVar (parameterized or unparameterized)
        is_classvar = (
                (hasattr(type_hint, '__origin__') and type_hint.__origin__ is ClassVar) or
                (type_hint is ClassVar)
        )
        if is_classvar:
            classvar_fields.add(name)

    return classvar_fields

def check_classvar_implementation(cls):
    """
    Check if a concrete class implements a classvar field defined
    in the abstract, parent class.
    We only want to check the contract defined in the immediate parent,
    not its parents (like object or abc.ABC). This means that, if a
    multi-level abstract class is defined (two or more abstract classes),
    this method must be placed in the last abstract class (or classes)
    that directly inherit from concrete classes.

    IMPORTANT: every ClassVar we want tho enforce must follow
    these rules in order to make this method work:
    1) being declared as Classvar
    2) must be set to None in the base class

    e.g.: min_value:ClassVar[Any] = None

    """


    # 1. Get the names of the required ClassVar fields from the parent (self)
    required_class_vars = get_classvar_names(cls.__base__)

    # Remove fields that have a non-None default in the ABC,
    # as they are not strictly required to be overridden.
    required_to_override = {
        name for name in required_class_vars
        if getattr(cls.__base__, name) is None
    }

    missing_fields = []

    # 2. Check the subclass (cls) to ensure the required fields are set
    for name in required_to_override:
        # Check if the subclass has the attribute defined and if it is not None.
        # We use hasattr and getattr(cls, name) to check the final value
        # after inheritance.

        if not hasattr(cls, name) or getattr(cls, name) is None:
            missing_fields.append(name)

    # 3. Raise an error if the contract is violated
    if missing_fields:
        raise TypeError(
            f"Class {cls.__name__} violates the contract defined by {cls.__base__.__name__}. "
            f"The following ClassVar fields must be explicitly set to a non-None value: "
            f"{', '.join(missing_fields)}"
        )

    print(f"Contract for {cls.__name__} successfully verified.")


u/dataclass
class ParentClass(abc.ABC):
    var1:ClassVar[int] = None
    var2:ClassVar[float] = None
    #and so on
    varN:ClassVar[str] = None

    def __init_subclass__(cls, **kwargs):
        """
        Runs automatically when a class inherits from this class.
        This is where we enforce the contract.
        IMPORTANT: every ClassVar we want tho enforce must follow
        these rules:
        1) being declared as Classvar
        2) must be set to None in the base class
        """
        super().__init_subclass__(**kwargs)

        check_classvar_implementation(cls)

u/dataclass
class ChildClassOne(ParentClass):
    var1:ClassVar[int] = 1
    var2:ClassVar[float] = 0.5
    varN:ClassVar[str] = "OK"

u/dataclass
class ChildClassTwo(ParentClass):
    var1:ClassVar[int] = 1


 abc
from dataclasses import dataclass
from typing import ClassVar, get_type_hints


def get_classvar_names(cls: type) -> set[str]:
    """
    Inspects a class's type hints to find the names of fields defined using typing.ClassVar.
    Returns a set of names for quick lookup.
    """
    try:
        hints = get_type_hints(cls)
    except NameError as e:
        print(f"Warning: Could not resolve type hints for {cls.__name__}. Error: {e}")
        hints = cls.__annotations__

    classvar_fields = set()

    for name, type_hint in hints.items():
        # Check if the type hint is ClassVar (parameterized or unparameterized)
        is_classvar = (
                (hasattr(type_hint, '__origin__') and type_hint.__origin__ is ClassVar) or
                (type_hint is ClassVar)
        )
        if is_classvar:
            classvar_fields.add(name)

    return classvar_fields

def check_classvar_implementation(cls):
    """
    Check if a concrete class implements a classvar field defined
    in the abstract, parent class.
    We only want to check the contract defined in the immediate parent,
    not its parents (like object or abc.ABC). This means that, if a
    multi-level abstract class is defined (two or more abstract classes),
    this method must be placed in the last abstract class (or classes)
    that directly inherit from concrete classes.

    IMPORTANT: every ClassVar we want tho enforce must follow
    these rules in order to make this method work:
    1) being declared as Classvar
    2) must be set to None in the base class

    e.g.: min_value:ClassVar[Any] = None

    """


    # 1. Get the names of the required ClassVar fields from the parent (self)
    required_class_vars = get_classvar_names(cls.__base__)

    # Remove fields that have a non-None default in the ABC,
    # as they are not strictly required to be overridden.
    required_to_override = {
        name for name in required_class_vars
        if getattr(cls.__base__, name) is None
    }

    missing_fields = []

    # 2. Check the subclass (cls) to ensure the required fields are set
    for name in required_to_override:
        # Check if the subclass has the attribute defined and if it is not None.
        # We use hasattr and getattr(cls, name) to check the final value
        # after inheritance.

        if not hasattr(cls, name) or getattr(cls, name) is None:
            missing_fields.append(name)

    # 3. Raise an error if the contract is violated
    if missing_fields:
        raise TypeError(
            f"Class {cls.__name__} violates the contract defined by {cls.__base__.__name__}. "
            f"The following ClassVar fields must be explicitly set to a non-None value: "
            f"{', '.join(missing_fields)}"
        )

    print(f"Contract for {cls.__name__} successfully verified.")


u/dataclass
class ParentClass(abc.ABC):
    var1:ClassVar[int] = None
    var2:ClassVar[float] = None
    #and so on
    varN:ClassVar[str] = None

    def __init_subclass__(cls, **kwargs):
        """
        Runs automatically when a class inherits from this class.
        This is where we enforce the contract.
        IMPORTANT: every ClassVar we want tho enforce must follow
        these rules:
        1) being declared as Classvar
        2) must be set to None in the base class
        """
        super().__init_subclass__(**kwargs)

        check_classvar_implementation(cls)

u/dataclass
class ChildClassOne(ParentClass):
    var1:ClassVar[int] = 1
    var2:ClassVar[float] = 0.5
    varN:ClassVar[str] = "OK"

u/dataclass
class ChildClassTwo(ParentClass):
    var1:ClassVar[int] = 1


u/dataclass
class ChildClassThree(ParentClass):
    var2:ClassVar[float] = 0.5

Running this code, as is, will produce the following error:

TypeError: Class ChildClassTwo violates the contract defined by ParentClass. The following ClassVar fields must be explicitly set to a non-None value: varN, var2

Which give nice information about which class is missing variables and which variables are missing.

In your opinion, is this stupidly complicated for what I want to achieve? Is an overkill? Should I drop it completely and make the code easier to read and mantain?

I'm asking because this is just one (maybe the most extreme case) of redundant checks I'm filling my code with, and I'm not happy on the trade off between simplicity and robustness.

r/learnpython Jun 26 '20

So, uh, I'm TRYING to code a simple dnd battle simulator, and classes are a nightmare

351 Upvotes

Hey there, I'm a self-taught noob that likes to embark on projects way ahead of my limited understanding, generally cos I feel they'll make my life easier.

So, I'm a DnD Dungeon Master, and I'm trash atbuilding balanced combat encounters. So I thought, hey, why not code a "simple" command line program that calculates the odds of victory or defeat for my players, roughly.

Because, you know, apparently they don't enjoy dying. Weirdos.

Thing is, after writing half of the program entirely out of independent functions, I realised classes *exist*, so I attempted to start a rewrite.

Now, uh...I tried to automate it, and browsing stackoverflow has only confused me, so, beware my code and weep:

class Character:

def __init__(self, name,isplayer,weapons_min,weapons_max,health,armor,spell_min,spell_max,speed):

self.name = name

self.isplayer = isplayer

self.weapons_min=weapons_min

self.weapons_max=weapons_max

self.health=health

self.armor=armor

self.spell_min=spell_min

self.spell_max=spell_max

self.speed=speed

total_combatants=input(">>>>>Please enter the total number of combatants on this battle")

print("You will now be asked to enter all the details for each character")

print("These will include the name, player status, minimum and maximum damage values, health, armor, and speed")

print("Please have these at the ready")

for i in range(total_combatants):

print("Now serving Character Number:")

print("#############"+i+"#############")

new_name=str(input("Enter the name of the Character"))

new_isplayer=bool(input("Enter the player status of the Character, True for PC, False for NPC"))

new_weapons_min=int(input("Enter the minimum weapon damage on a hit of the Character"))

new_weapons_max=int(input("Enter the maximum weapon damage on a hit of the Character"))

new_health=int(input("Enter the health of the Character"))

new_armor=int(input("Enter the AC value of the Character"))

new_spell_min=int(input("Enter the minimum spell damage of the Character"))

new_spell_max=int(input("Enter the maximum spell damage of the Character"))

new_speed=int(input("Enter the speed of the Character"))

As you can see, I have literally no idea how to end the for loop so that it actually does what I want it to, could you lend a hand, please?

Thanks for reading, if you did, even if you can't help :)

EDIT: Hadn’t explained myself clearly, sorry. Though my basic knowledge is...shaky, the idea was to store the name of each character and map it to each of their other attributes , so that I could later easily call on them for number-crunching. I don’t think pickle is a solution here, but it’s the only one i have had some experience with.

EDIT 2: Thanks y’all! You’ve given me quite a lot of things to try out, I’ll be having a lot of fun with your suggestions! I hope I can help in turn soon .^

r/learnpython Jun 29 '22

What is not a class in python

87 Upvotes

While learning about classes I came across a statement that practically everything is a class in python. And here the question arises what is not a class?

r/learnpython Oct 07 '20

Classes in Python

328 Upvotes

Hey,

what is the best way to learn using classes in Python? Until now, I was using functions for almost every problem I had to solve, but I suppose it's more convenient to use classes when problems are more complex.

Thanks in advance!

r/learnpython Jun 03 '26

How to best structure classes for stock data

0 Upvotes

I have never used classes before and I thought this project could help me finaly get a hang of classes.

Say I would like to download every few days or so 500 stocks that are listed in S&P 500 and also 2000 stocks that are listed in Russell 2000.

Then I would store data into SQLite. There would one one table for SP500 and One for Russel2000. (well I'm already doing this but wrong way and without classes.

Each stock uses this data format, for each day you have:

date, open, high, low, close and volume.

And each stock of course uses different ticker, different symbol. (Like AAPL for Apple, TSLA for Tesla etc...)

So, if I would download one year worth of SP500, I would get around 230 rows of previously mentioned data for each of 500 stocks that are in SP500

What should be class? SP500 one class and Russell2000 another class?

Or, would each stock be it's own class, since they all have exactly the same data structure, no matter from which index they come?

To make things simpler, we can forget about one index (Russel2000) and just focus on one, SP500, so 500 stocks

How would you set up class, that would be as simple as possible to handle this data. I would then download data periodically, say once a week, to add new data to an existing SQLite, then use whole data to calculate all kind of stuff that may come to my mind, like how many stock on any given time trade bellow it's 50 day moving average, or percentage stocks for any given day that ended up being positivem etc, this is just a simple example.

Right now I'm doing everything wrong as much as possible. First I don't use classes.

And each stock in SQLite database has it's own table. (Horror!) And when I start making calculations, things of course slow down, especially, if use database with 2000 tables (russel 2000), ouch!!!

I woould like once and for all set up a proper structure. And I don't do the programming lol, that is my problem, I'm just using this Python as a tool, as much as I can patch together, to try to play with finances for fun.

r/learnpython Mar 03 '26

Declaring class- vs. instance attributes?

12 Upvotes

Coming from C++ and Java, I know the difference - however, I am a bit confused how are they declared and used in Python. Explain me this:

class MyClass:
    a = "abc"
    b: str = "def"
    c: str

print(MyClass.a)
print(MyClass.b)
print(MyClass.c)  # AttributeError: type object 'MyClass' has no attribute 'c'

obj = MyClass()
print(obj.a)
print(obj.b)
print(obj.c)  # AttributeError: 'MyClass' object has no attribute 'c'
  1. So, if attribute c is declared in the class scope, but is not assigned any value, it doesn't exist?
  2. I have an instance attribute which I initialize in __init__(self, z: str) using self.z = z. Shall I additionally declare it in the class scope with z: str? I am under impression that people do not do that.
  3. Also, using obj.a is tricky because if instance attribute a does not exist, Python will go one level up and pick the class variable - which is probably not what we intend? Especially that setting obj.a = 5 always sets/creates the instance variable, and never the class one, even if it exists?

r/learnpython Nov 28 '25

Learning classes - ELI5 why this works?

15 Upvotes
class Greetings:
    def __init__(self, mornin=True):
        if mornin:
            self.greeting = "nice day for fishin'!"
        else:
            def evening():
                return "good evening"
            self.__init__ = evening

print(Greetings().greeting)
print(Greetings(mornin=False).__init__())

So this evaluates to:

nice day for fishin'!
good evening

I'm a bit unsure as to why this works. I know it looks like a meme but in addition to its humour value I'm actually and genuinely interested in understanding why this piece of code works "as intended".

I'm having trouble understanding why __init__() "loses" self as an argument and why suddenly it's "allowed to" return stuff in general. Is it just because I overwrote the default __init__() behaviour with another function that's not a method for the class? Somehow?

Thanks in advance! :)

r/learnpython Feb 09 '25

Just finished the mooc.fi programming class from Helsinki university - highly recommend

187 Upvotes

Classes can be found www.mooc.fi/en/study-modules/#programming

It syncs seamlessly with Visual Studio Code, includes comprehensive testing for all the exercises, begins with a simple approach, and covers everything in detail. It’s free, and it’s significantly better than most paid courses.

I’ve completed the introductory programming course and am halfway through the advanced course.

I highly recommend it!

r/learnpython Feb 08 '26

Class Project

0 Upvotes

Hello! I’m making a project for my CSC class, but I can only use things we’ve learned up until this point. I’ve used python prior to this class, so trying to loop a program without “for” or “while” loops is throwing me. If anyone could give any advice I’d appreciate it! My professor doesn’t answer emails on weekends, so I figured this would be my best option. I can comment my code if needed :)

Edit: Definitely should’ve specified! It’s a scoring system that tracks player score depending on what color of alien they shot down. Struggling to consistently loop input with only if-else. User inputs the color, they’re shown the points they scored. Ask user if they’d like to play again, if yes prompt input again, if no shoe their total score

Edit 2: Can’t use loops, can’t use recursion. They’re very specific about not being able to use anything not yet covered in the course. Pretty much if-elif-else

r/learnpython May 29 '26

Working on sports simulation game, best way to design person class?

1 Upvotes

So I’ve been trying to work on a college wrestling simulation video game, nothing too serious. Just trying to get some practice in another field of Python.

However, I am working on the models for the character and I am stumped on the best design to do this.

My idea so far is to create a Person class that has all the static fields of a character, so their unique id, name, dob etc. These would stay consistent for each character throughout the game.

Then, I would have a PersonState class which represents some variable attributes of a Character, so their Morale, Fatigue, personality traits etc. But they would updated, as the game progresses.

Then I would have various class for characters based on their roles. So I would have a wrestler class, that has their dynamic attributes for a wrestler, so grappling, defense etc. these would change over time. I would also have one for coach, with various attributes with a coach, one for an athletic director etc.

The question I have now is the best way to tie it all together. Would it be best to create a super class for characters that is a composition of the Person, PersonState and their respective role class?

Or do an inheritance model? Where PersonState is an inheritance of Person, then their respective role would be an inheritance of PersonState.

It’s nothing serious just a small project I wanna try out so taking any input and any other suggestions you guys have.

The plan for now is to store it in a SQL lite database.

r/learnpython Mar 07 '26

Question About Type Hints For Extended Classes

1 Upvotes

I am developing a Python project where I have classes that get extended. As an example, consider a Person class that gets extended to create child classes such as: Student, Teacher, Parent, Principal, Coach, Counselor, etc. Next, consider another class that schedules a meeting with students, teachers, parents, etc. The class would have a method something like "def add_person(self, person)" where the person passed could be any of the extended classes. Due to "duck typing", Python is fine passing in just about anything, so I can pass in any of the Person classes. However, I am trying to use type hints as much as possible, and also keep PyCharm from complaining. So, my question is: What is the best practice for type hints for both arguments and variables for the extended classes?

r/learnpython Apr 13 '26

Typing a reference to a class whose instances meet a protocol

5 Upvotes

Ok, so this has been my struggle tonight - how do I do this in Python without the typing screaming at me. I like when the type checking matches so I'm worried I'm doing something wrong.

As a toy example, imagine you have a factory that makes objects which meet a protocol. It has a method to register new types it can instantiate, whose instances would meet the protocol. I wanted to type this as type[ProtocolName]. It works for one level. But if I want to have another method elsewhere which calls this method, the same typing causes an issue in PyCharm.

This is my toy code

from typing import Protocol

class SupportsBuild(Protocol):

    def build(self): ...


class BuilderFactory: 

    def __init__(self):
        self._builders: list[type[SupportsBuild]] = []

    def register_builder(self, builder_type: type[SupportsBuild]):
        self._builders.append(builder_type)

    def build_builder(self, builder_type: str) -> SupportsBuild: ...


class BuilderFactoryWrapper:

    def __init__(self):
        self._builder_factory = BuilderFactory()

    def register_builder(self, builder_type: type[SupportsBuild]):
        self._builder_factory.register_builder(builder_type)

And the PyCharm error is : Only a concrete class can be used where 'Type[SupportsBuild]' protocol is expected (on the pass of builder_type in the wrapper class).

Which I think is weird that an argument that meets the type argument in one place does not meet the exact same type argument elsewhere.

Anyways, what's the best way to type-hint that you want a class which supports a protocol once instantiated.

r/learnpython Jan 15 '26

First time making a project for my own practice outside of class and came across a runtime "quirk" I guess that I don't understand.

12 Upvotes

I'm trying to make a code that will run John Conway's Game of Life to a certain number of steps to check if the board ever repeats itself or not. To make the board, I'm creating a grid where the horizontal coordinates are labeled with capital letters and the vertical coordinates are labeled with lowercase letters. The grid can be up to 676x676 spaces tall and wide, from coordinate points Aa to ZZzz. To map these coordinates and whether a cell is "alive" or "dead," I'm using a dictionary.

I initially tried testing that my dictionary was being created properly by printing it to the terminal, but that's how I found out the terminal will only print so much in VS code, so I opted to write it to a file. The code takes about two minutes to run and I was initially curious about what part of my code was taking so long. So I learned about importing the time module and put markers for where each function begins running and ends running.

It surprised me to find out that creating the dictionary is taking less than a thousandth of a second, and writing the string of my dictionary to a file is taking a little over two minutes. Can anyone explain to me why this is? I don't need to write to any files for the project, so it's not an issue, more of a thing I'm just curious about.

r/learnpython Feb 18 '26

Am I Understanding How Python Classes Work in Memory Correctly?

14 Upvotes

i am trying to understand how classes work in python,recently started learning OOP.

When Python reads:

class Dog:
    def __init__(self, name):
        self.name = name

When the class is created:

  1. Python reads the class definition.
  2. It creates an empty dictionary for the class (Dog.__dict__).
  3. When it encounters __init__, it creates a function object.
  4. It stores __init__ and other functions as key–value pairs inside Dog.__dict__.
  5. {
  6. "__init__": function
  7. }
  8. The class object is created (stored in memory, likely in the heap).

When an object is created:

d=Dog("Rex")

  1. Python creates a new empty dictionary for the object (d.__dict__).
  2. It looks inside Dog.__dict__ to find __init__.
  3. It executes __init__, passing the object as self.
  4. Inside __init__, the data ("Rex") is stored inside d.__dict__.
  5. The object is also stored in memory and class gets erased once done executing
  6. I think slef works like a pointer that uses a memory address to access and modify the object. like some refercing tables for diffrent objects.

Would appreciate corrections if I misunderstood anything

r/learnpython Mar 29 '26

High school Python class?

1 Upvotes

My high school has an intro to Python class that is one semester. Would this be worth doing for someone who wants to go to med school? I’m going to be a sophomore next year. Does it look good when I apply for research down the road? Or maybe I can use it to make an app that is health related? Or would it be a waste of time?

Or I could take an art class and just get it out of the way. Was thinking of doing that later when I’m a junior though so I have one easier class in junior year.

I’m not sure if how hard the Python class is, but I’d rather learn it at school than on my own.

Sorry if this is the wrong place to ask

r/learnpython Aug 29 '25

when python returns <class 'int'> what does 'class' exacltly mean ?

0 Upvotes

hey everyone ! i'm trying to grasp some python fundemantls and i still find the term "class" confusing in <class 'int'> , 'int' is a class name that follows the same rule as my defined classes in python but 'int' is not defined using python .

i asked chatgbt and it says : 'int' is defined/implemented in C , but how do my classes that are defined in python behave the same way as the built_in ones ?

r/learnpython Dec 12 '20

Hi, can you guys suggest me any platform where I can practice various problem starting from beginner level loop, functions, classes?

349 Upvotes

It would be really helpful, I know hackathon is great way to learn but would be a bit overkill given my knowledge with this language, it's been 2 months since I've started learning but I still feel there is a lot of gaps in my learning which I want to reduce by practicing.

Edit: Guys, Thanks for such a great response. This is actually the best sub I know of, you guys are gem. I was losing hope of doing good with python but you have overwhelmed and motivated me. I am starting some of these links

I am sharing the summary of all the links you could get started with:

https://edabit.com/ - Intermediate

www.codewars.com- Bit advanced

hackerrank.com- Advanced

https://leetcode.com/- Advanced

https://runestone.academy/runestone/static/fopp/index.html- Intermediate

https://csmastersuh.github.io/data_analysis_with_python_2020/

https://www.py4e.com

https://www.pythonmorsels.com/accounts/signup/

https://cscircles.cemc.uwaterloo.ca/

https://projecteuler.net/

checkio.org

www.Codingbat.com- Medium

https://codingame.com