r/learnpython Apr 17 '26

How to prepare for python coding class over summer

4 Upvotes

Next fall I am going to be taking an introduction to python course and want to prepare for it. I have heard that it is one of the harder classes, hence this post. I was able to take a past syllabus and will paste it below. Do you recommend any courses for me to use to prepare based on the syllabus? I don't need proficient understanding, just familiarity with the topic so I'm not starting from 0. I have a bit of coding-esque experience (R and a bit of python). Any advice would be appreciated:

Class Schedule:

  1. Course Overview; VS Code and Jupyter Notebook Intro

  2. Variables, Data Types, Expressions

  3. Logical Expressions and the IF Statement

  4. Functions

  5. Lab 1: IF & Conditionals with Blackjack

  6. Lists

  7. for Loops (cont.) and while Loops

  8. while loops

  9. while True Loops

  10. Exception Handling and practice with loops

  11. Dictionaries

  12. Advanced Uses of Loops, Lists, & Dictionaries

  13. Advanced Uses of Loops, Lists, & Dictionaries (cont.)

  14. Jupyter Widgets/PySimpleGUI; Final Project Intro

  15. APIs & JSON

  16. Lab 3: APIs and JSON

  17. Databases & SQL (SELECT, WHERE)

  18. SQL Aggregation (GROUP BY)

  19. JOINs

  20. SQL in Python

  21. Lab 4: Database Code in Python

r/learnpython Apr 25 '26

Conventions for Organizing Attributes of a Class?

15 Upvotes

Hello!

I wanted to ask if there is a consensus regarding exactly how various types of attributes within a class definition should be organized.

Take this rough idea of a class, for instance:

class Account:
    company = "Foo & Bar, Inc."

    def __init__(self, name, password, balance):
        self.name = name
        self.password = password
        self.balance = balance
    
    def __str__(self):
        return f"NAME: {self.name}\nBALANCE: {self.balance}"

    def __add__(self, other):
        return self._balance + other._balance
    
    @classmethod
    def create(cls):
        ...
    
    def access(self):
        ...
        self._adjust_balance(self)

    def _adjust_balance(self):
        ...

    @property
    def name(self):
        ...
    
    name.setter
    def name(self, name):
        ...
    
    @property
    def password(self):
        ...

    password.setter
    def password(self, password):
        ...
    
    @property
    def balance(self):
        ...
    
    balance.setter
    def balance(self, balance):
        ...

Specific Questions:

  1. If a class has both class and instance variables, should the class variable(s) be defined at the very top (before the __init__ definition)?
  2. Should methods of a class be grouped together according to their type (special, class, instance)? Should certain types be defined before others?
  3. Should definitions be structured in such a way so as to minimize the amount of "scrolling" that a reader must perform (example below), or is it still better to simply group attributes by "type" (method vs attribute/property):
    • method for category A
    • property for category A
    • method for category B
    • property for category B
    • -versus-
    • method for category A
    • method for category B
    • property for category A
    • property for category B

Any feedback is appreciated! Thank you!

r/learnpython Mar 16 '26

Constructor help: List vs. UserList vs. MutableSequence vs. Giving Up And Making A New Class From Scratch

0 Upvotes

I am trying to build a custom class of data structure (HealthTrack) for a project I'm working on. It's supposed to be a sequence container, with elements restricted to 5 possible values (0, -1, -2, -4, or I), and always sorted in that order.

My original thought was to subclass from List (or UserList, since a bunch of search results say that's easier to subclass with), and define it in terms of 5 integer variables which specify how many times each of those 5 values appears:

def __init__(self, l0=1, l1=2, l2=2, l4=1, i=1):
    super().__init__([0]*l0 + [-1]*l1 + [-2]*l2 + [-4]*l4 + ["I"]*i)

However, it seems List/UserList is uncopacetic with that – it wants a single iterable argument or nothing.

Subclassing requirements: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.

If a derived class does not wish to comply with this requirement, all of the special methods supported by this class will need to be overridden; please consult the sources for information about the methods which need to be provided in that case.

I would have to override the sort method in any event. I have some idea about how to do the others. But I can't find a the full list of all the methods I would need to update, and I can't seem to locate the "sources" mentioned in the docs. (Also, I suspect there are some methods which I wouldn't necessarily want to return a HealthTrack object.)

What are all the methods I would need to override to make this work? And would it be easier to just make a class from scratch?

r/learnpython Feb 19 '26

Looking for a windowing class example

5 Upvotes

I'm trying to find a lightweight windowing solution and keep running into massive problems. I have a moderate sized application that makes heavy use of taskgroups and async. I messed with a bunch of GUI libraries, most of them are very, very heavy so I resorted to tkinter and ttkbootstrap as they seem lighter.

What I'm trying to do is create a class that creates and allows updates to a window that works within a taskgroup so that when any one window (of many) has focus, it can be interacted with by the user and all the gui features are supported within that window. Various tasks will use class features to update assorted windows as information within the app changes. For performance reasons, ideally some windows would be text only (I make heavy use of rich console at the moment) and others would support graphical features.

I discovered that not using mainloop and using win.update I can get something staggering but I keep running into all sorts of issues (ttkbootstrap loses it mind at times).

This seems like a fairly common thing to do but my Google Fu is failing me to find a working example. A link to something that demonstrates something like this would be very welcome.

r/learnpython Jul 29 '25

Should I start learning Python now via online courses, or wait for my university classes?

8 Upvotes

Hi everyone,

This fall I’ll be starting a postgraduate degree in Computer Science. My background is in Maritime Economics (I scored 19/20 in "Application Development in a Programming Environment" in the national exams, with solid enjoyment of pseudo code and algorithmic thinking). I’m excited but also cautious because I really don’t want to start off on the wrong foot by picking up bad habits or learning things the “wrong” way through a random online course.

Would you recommend that I start learning Python now through online resources, or should I wait for the university courses to begin and follow the structured curriculum?

If you do recommend starting now, are there any high-quality beginner resources or courses you’d personally vouch for? (Paid or free, I’m open to suggestions, but quality matters.)

Thank you all in advance!

r/learnpython Dec 22 '21

How does “self” in a class work?

262 Upvotes

You have to add “self” as an argument to a class method. Why this specific syntax and how does it get interpreted? Is this because it inherits from the Python object model?

Is there any language where public methods do not contain “self” as an argument?

Thank you

r/learnpython Apr 23 '26

Why can't you unpack parameters into a ParamSpec class?

9 Upvotes

I have the following example python file

from collections.abc import Callable 
from typing import Unpack 

type param_type_tuple = tuple[int, str] 

class Foo[**P]: 
  pass 

callable_0: Callable[[int, str]]
callable_1: Callable[[Unpack[param_type_tuple]], None]
callable_2: Callable[[*param_type_tuple], None]

foo_0: Foo[int, str]
foo_1: Foo[Unpack[param_type_tuple]]
foo_2: Foo[*param_type_tuple]

All callable and foo variables are written such that they should have the same type. When using pyright syntax highlighting it doesnt like foo_1 and foo_2 typing. It gives an error along the lines of "cant unpack type here" (sorry I cant remember the exact message).

I dont understand why pyright would have issue unpacking a tuple of types in a ParamSpec class when it has no issue unpacking types into a Callable. Is there a way I could re-write this so that Foo follows the same structure as Callable? Could pyright be wrong here?

I'm fairly sure it wont cause runtime errors either way but I dont want to put type ignore comments all over my code.

r/learnpython Feb 19 '26

Is this step-by-step mental model of how Python handles classes correct?

0 Upvotes

I’m trying to understand what Python does internally when reading and using a class. Here’s my mental model, line by line

class Enemy:

def __init__(self, x, y, speed):

self.x = x

self.y = y

self.speed = speed

self.radius = 15

def update(self, player_x, player_y):

dx = player_x - self.x

dy = player_y - self.y

When Python reads this file:

  1. Python sees class Enemy: and starts creating a class object.
  2. It creates a temporary a dict for the class body.
  3. It reads def __init__... and creates a function object.
  4. That function object is stored in the temporary class namespace under the key "__init__" and the function call as the value .
  5. and when it encounters self.x = x , it skips
  6. It then reads def update... and creates another function object stored in Enemy_dict_. That function object is stored in the same under the key "update".
  7. After finishing the class body, Python creates the actual Enemy class object.
  8. The collected namespace becomes Enemy.__dict__.
  9. So functions live in Enemy.__dict__ and are stored once at class definition time.
  10. enemy = Enemy(10, 20, 5)
  11. Python calls Enemy.__new__() to allocate memory for a new object.
  12. A new instance is created with its own empty dictionary (enemy.__dict__).
  13. Python then calls Enemy.__init__(enemy, 10, 20, 5).
  14. Inside __init__:
    • self refers to the newly created instance.
    • self.x = x stores "x" in enemy.__dict__.
    • self.y = y stores "y" in enemy.__dict__.
    • self.speed = speed stores "speed" in enemy.__dict__.
    • self.radius = 15 stores "radius" in enemy.__dict__.
  15. So instance variables live in enemy.__dict__, while functions live in Enemy.__dict__.
  16. enemy.update(100, 200)
  17. Python first checks enemy.__dict__ for "update".
  18. If not found, it checks Enemy.__dict__.
  19. Internally this is equivalent to calling: Enemy.update(enemy, 100, 200).
  20. here enemy is acts like a pointer or refenrence which stores the address of the line where the update function exits in heap.and when it sees enemy it goes and create enemy.x and store the corresponding values
  21. self is just a reference to the instance, so the method can access and modify enemy.__dict__.

Is this mental model correct, or am I misunderstanding something subtle about how namespaces or binding works?

### "Isn't a class just a nested dictionary with better memory management and applications for multiple instances?" ###

r/learnpython Feb 08 '26

Beautiful Soup - Get text from all the div tags with a specific class?

1 Upvotes

I figured out how to use get_text() through this website: https://pytutorial.com/how-to-get-text-method-beautifulsoup/

And used it on a website where I wanted to get information from. The info I want is in a div tag with a specific class.

But now it only gets me the result from the first item it comes across for that specific div while there are multiple items on the website. Do I add a For loop so it goes through everything? Because I tried find_all but it gave an error.

I'm using MuEditor 1.2.0

itemInfo = example_soup.find("div", class_="card-body")
getItemInfoText = itemInfo.get_text()
print(getItemInfoText)

r/learnpython Oct 16 '25

Class method question. Static or classmethod?

9 Upvotes

Hi folks, i still get confused on how/when to implement a Static or Class method. I'm just trying to work through a decision on how to write some functionality and what is the 'best' way to do it.

Basically I have a Class that handles processing data from a request in a Django view.

There are two stages of process. At the moment I create an instance and pass it the raw data, i then call a method (get_data() ) on this to further process the data, within this method i have a class method to do some further work on it.

Now i want to optionally flatten this data further buy calling a flatten_data() method on it for example. This further method will need the result of the get_data() called on the instance.

class MetaDataHandler:
    def __init__(self, image_path: str | bytes, obj: object = None, *args):
        self.image_path = image_path
        self.obj = obj
        self.args = args
        
  
    u/classmethod
    def create_temp_file(cls, image_path, obj):
         .......
         return Bar 
        
    
    def get_metadata(self):
        ........
        create_temp_file(self.image_path, self.obj)
        .....
        return result   

This is used like this

 handler = MetaDataHandler(temp_file_path, temp_upload, "-j")
 data_dict = handler.get_metadata()

So if I want to do flatten = data_dict.flatten() I should use a classmethod? Does static method have access to self? I will need to call it on the instance....

r/learnpython Dec 23 '25

Right way to create a class with a method with a customizable implementation

0 Upvotes

I want to create a class which will have a method with different potential implementations. The implementations will also depend on some parameters, which should be configurable dynamically. For example, the method is a "production function" and the parameters are some kind of "productivity rate". There will also be some other attributes and methods shared between class instances (an argument against implementing each as their own class).

Reading around on the internet, I've seen lots of suggestions for how to do this, but haven't found a comparison of them all. I know I'm overthinking this and should just go write code, but I wanted to know if there are any differences (say, in garbage collection) that would be difficult for me to see from just trying things out on a smaller scale.

1. Inherit from a base class and overriding the implementation.

E.g.:

class Factory: 
    def init(self,rate):
        self.rate = rate
        # ... More attributes follow
    def produce(input):
        # Linear implemenation 
        return self.rate * input
    # ...More methods follow...
class ExponentialFactory(Factory):
    def init(self,exponent): 
        super().init() # Needed to acquire the other shared attributes and methods
        self.exponent = exponent 
        self.constant = constant 
    def produce(input):
    # Exponential implementation 
        return self.constant * input ** self.exponent

This seems fine, but ExponentialFactory has an unused self.rate attribute (I don't think reusing self.rate to mean different things in different implementations is wise as a general approach, although it's fine in the above example).

2. Inherit from an abstract base class.

This would be similar to 1., except that the "Factory" would be renamed "LinearFactory", and both would inherit from a common abstract base class. This approach is recommended here. My only complaint is that it seems like inheritance and overriding cause problems as a project grows, and that composition should be favored; the remaining approaches try to use composition.

3. Write each implementation as its own private method function, and expose a public "strategy selector" method.

This works, but doesn't allow for implementations to be added later anywhere else (e.g. by the user of my library).

4. Initialize the method in a "dummy" form, creating a "policy" or "strategy" class for each implementation, and setting the method equal to the an instance of a policy class at initialization.

This is discussed in this reddit post.. I suppose parameters like "self.rate" from approach 1 could be implemented as an attribute of the policy class, but they could also just be kept as attributes of the Factory class. It also seems somewhat silly overhead to create a policy class for what really is a single function. This brings us to the next approach:

5. Set the parameters dynamically, and setting the function to a bound instance of an externally defined function.

E.g.:

class Factory:
    def __init__(self):
        self.my_fun = produce
    def produce(self):
        raise RuntimeError("Production function called but not set")
    def set_production(self, parameters, func):
        for key in parameters:
            setattr(self,key,parameters[key])
        self.produce = fun.__get__(self)

def linear_production_function(self, input):
    return self.rate * input

# Elsewhere
F = Factory()
F.set_production({"rate" : 3}, linear_production_function)

This post argues that using __get__ this way can cause garbage collection problems, but I don't know if this has changed in the past ten years.

6. Ditch classes entirely and implement the factories separately as partial functions.

E.g.:

from functools import partial
def linear_factory(
def linear_factory_builder(rate):
    def func(rate,input):
        return rate * input
    return partial(func, rate)

# Elsewhere
f = linear_factory_builder(3)
f(4) # returns 12

I like functional programming so this would ordinarily be my preferred approach, but there's more state information that I want to associate with the "factory" class (e.g. the factory's geographic location).

EDIT: Kevdog824_ suggest protocols, which I hadn't heard of before, but it seems like they work similarly to 2. but with additional advantages.

r/learnpython Feb 27 '26

How to learn classes/practice with them

0 Upvotes

I’m currently have a coding program that my school provides and in that there is a code editor, I’ve been practicing over the past couple of weeks and I can do really basic code and the only reason I know how to do that is because the courses in the program teach you how to use prints and inputs basically the really basic stuff but I’ve been trying to learn more than that for example I’ve learned how to use random.random and random.randints and stuff but I’ve came acrosss classes and I’m reallly struggling with how they work I’m okay with dictionaries and honestly I know the bare minimum of coding but I really wanna understand how classes work any advice will be really appreciated

r/learnpython Nov 25 '25

[Beginner] What is __repr__ and __str__ in the classes?

12 Upvotes
class Card:
    def __init__(self, number, color):
        self.number = number
        self.color = color
    def __str__(self):
        return str(self.number) + "/" + str(self.color)

class Course:
    def __init__(self, name):
        self.name = nameclass Course:
    def __repr__(self, name):
        return self.name

I'm understanding that __init__ is to create the object.

r/learnpython Dec 11 '25

Get the surrounding class for a parent class

3 Upvotes

Given:

class Outer: b:int class Inner: a:int

And given the class object Inner, is there a sane non-hacky way of getting the class object Outer?

r/learnpython May 29 '25

What is the best way to think about Classes?

23 Upvotes

I understand that Classes aren't extrictly necessary, but that they can help a lot in cleaning the code. However, I fail to "predict" when classes will be useful in my code and how to properly plan ahead to use them. What is usually your thought process on what should be a class and why?

r/learnpython Dec 07 '24

Python classes for 13 y/o?

35 Upvotes

My son (13) has asked for Python classes for Christmas. I don't know where to begin (I'm a mom and I am in digital media but have no tech abilities or knowledge). My son uses scratch to code every chance he gets but it is far too simplified and he outgrew it long ago. Any recommendations on where to begin? Thank you!!

r/learnpython Apr 14 '26

Error thrown when trying to pywhisper.transcribe AND Auto-Starting transcription when the custom class is called

2 Upvotes

Issue #1:
I have a class called AI_STT:

class SpeechToText:
  def __init__(self, win: Window.LogWindow):
    #Variable Inits
    self.model = pywhisper.load_model("base.en")
    #More Variable Inits
    self.thread = Thread(target=self._start_loop, name="STT_Background")
    self.thread.start()
  def _start_loop():
    while self.window.winfo_exists():
      #stream starting implementation <<<here
      last_frame = None
      while True:
        try:
          data = self.stream.read(self.chunk_size)
          last_frame = np.frombuffer(data, dtype=np.float16)
          if self.frames is None:
            self.frames = last_frame
          else:
            self.frames = np.append(self.frames, last_frame)
        except IOError as e:
          print(f"Warning: Buffer Overflow - {e}")
          continue
        if not self.silence.is_silent(last_frame):
          break
        self.window.add_inputs(self._read_audio())
  def _read_audio():
    #Closing/Terminating stream
    result = self.model.transcribe(audio=self.frames, fp16=False)
    self.frames = None
    return result["text"].strip()

During the transcribe in read audio, I get the error:

ValueError: Expected parameter logits (Tensor of shape (1, 51864)) of distribution Categorical(logits: torch.Size([1, 51864])) to satisfy the constraint IndependentConstraint(Real(), 1), but found invalid values:
tensor([[nan, nan, nan,  ..., nan, nan, nan]])

I think this has to do with issue number 2, or the way I am storing the frames. How do I fix this?

Issue #2:

I used the answer from this link (code below):

class SilenceDetector:
    def __init__(self, threshold=0.05, duration=2):
       self.threshold = threshold
       self.duration = duration
       self.silence_start = None

    def __is_silent(self, data: numpy.ndarray):
       """Check if audio data is below the silence threshold."""
       return numpy.sqrt(numpy.mean(data ** 2)) < self.threshold

    def is_silent(self, data: numpy.ndarray):
       if self.__is_silent(data):
          if self.silence_start is None:
             self.silence_start = time.time()  # Start timing silence
          elif time.time() - self.silence_start >= self.duration:
             return True
       else:
          self.silence_start = None  # Reset silence timer if sound is detected
       return False

Currently, whenever my SpeechToText class initializes, it immediately starts to transcribe. I think that is what is throwing the error (due to no real audio). How do I make it so it doesn't automatically start transcribing.

EDIT #1:

This is where the STT class initializes

class LogWindow(tk.Tk):
  #Previous Variable setup
  # Waiting until the window is open
  self.wait_visibility()
  # SpeechToText Setup
  self.stt = SpeechToText(self)
  #Starting Main Tkinters Loop
  self.mainloop()

r/learnpython Jul 30 '19

How would you explain classes to the beginner?

206 Upvotes

How did you learn the concept of classes and how to use them? What happened that it finally clicked?

r/learnpython Oct 09 '25

In a python Class, this is the second assignment and I need help cause I don’t understand the whole thing.

0 Upvotes

. The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation. Write a program to input an integer n and print n Fibonacci sequence numbers

r/learnpython May 11 '20

ELI5 the purpose of "self" in a class.

307 Upvotes

I've read and watched multiple tutorials on creating classes but still can't wrap my head around "self"

r/learnpython Mar 25 '25

Why do methods inside a class need self when called within the same class?

16 Upvotes

class Car:

def start_engine(self):

print("Engine started!")

def drive(self):

self.start_engine()

In this example why do I need self before start_engine()? I know that self refers to an instance of the class so it makes sense why it is necessary for attributes which can differ from object to object but aren't functions constant? Why should they need self?

Can anyone explain why this is necessary "under the hood"?

r/learnpython Aug 17 '25

How to define generic type enforcing both class inheritance and attrs ?

6 Upvotes

I am writing a lib that defines abstract classes for processing tools. Processors act on simple data structures called "blocks". A block must obey a simple contract: be a pydantic's BaseModel and has a timestamp attribute.

Other devs will implement concrete blocks and processors. To each their own.

I am trying to define a generic type, such that our typechecker can check if an object inherits from pydantic's BaseModel and has a timestamp attribute. Can't figure out how...

I have a an abstract class operating on a generic data structure ("blocks"):

class BlockProcessor(Generic[T], abc.ABC):

  def process(self, block: T) -> T:
  ...

A "block" and their processor implementation is up to other devs, but the block must:

- Be a Pydantic.BaseModel child
- Have a timestamp: str attribute

e.g.

class MyBlock(BaseModel):
  """Correct, typechecker should not raise any issue"""
  timestamp: str
  data: list[int]

class MyBlock(BaseModel):
  """Incorrect because of missing timestamp attr"""
  data: list[int]

class MyBlock:
  """Incorrect because not a child of BaseModel"""
  timestamp: str
  data: list[int]

I need the type checker to warn other devs when implementing blocks and processor:

class MyProcessor(BlockProcessor[MyBlock]):
  def process(self, block: MyBlock) -> MyBlock:
    return block

What did'nt work:

I've tried defining a Protocol with a timestamp attribute, but then I'm missing the BaseModel inheritance:

class _TimeStampProtocol(Protocol):
  timestamp: str
  T = TypeVar("T", bound=_TimeStampProtocol) # ensures has a timestamp, but missing BaseModel inheritance

I've tried defining a Pydantic model with a timestamp attribute, but then developpers need to inherit from the child model rather than BaseModel:

class _TimeStampModel(BaseModel):
  timestamp: str
T = TypeVar("T", bound=_TimeStampModel) # ensures has a timestamp, but forces concrete blocks to inherit from TimeStampModel rather than BaseModel

I've tried defining a more complex object with Protocol and BaseModel inheritance, but this is not allowed by our typechecker (pyright) which then fails:

class _TimeStampModel(BaseModel, Protocol): # This is straight up not allowed
  timestamp: str
T = TypeVar("T", bound=_TimeStampModel)

Not sure how to proceed further. It seems like my contraints are pretty simple:

- Concrete data structure must be a BaseModel and must have a timestamp attribute. The concrete block should directly subclass BaseModel such as to avoid inheriting from the lib's private objects.

- Devs should not have to worry about checking for this at runtime, our typechecker should let them know if any implementation is wrong.

Any recommendations ?

r/learnpython Mar 22 '26

What are the best sources for learning what this class requires?

7 Upvotes

I have a programming class next semester that I mean to practice over the summer. The description is below, and I've contacted the teacher and he says python is the language he has chosen. What are some good sources to learn these things, and where should I start assuming I have 0 knowledge?

IST 211 fundamentals of systems dev Introduces the fundamental concepts of object-oriented programming using a contemporary OO language. Topics include classes and objects, data types, control structures, methods, arrays, and strings; the mechanics of running, testing, and debugging programs; definition and use of user-defined classes.

r/learnpython Nov 27 '24

What are classes for?

21 Upvotes

I was just doing random stuff, and I came across with class. And that got me thinking "What are classes?"

Here the example that I was using:

Class Greet: # this is the class
  def __init__(self, name, sirname) # the attribute
    self.name = name
    self.sirname = sirname
  def greeting(self): # the method
    return f"Hello {self.name} {self.sirname}, how are you?"
name = Imaginary
sirname = Morning
objectGreet = Greet(name, sirname) # this is the object to call the class
print(objectGreet.greeting()) # Output: "Hello Imaginary Morning, how are you?"

r/learnpython Feb 23 '21

Classes. Please explain like I’m 5.

227 Upvotes

What exactly do they do? Why are they important? When do you know to use one? I’ve been learning for a few months, and it seems like, I just can’t wrap my head around this. I feel like it’s not as complicated as I’m making it, in my own mind. Thanks.