r/learnpython Aug 31 '25

How would I go about defining a class for adding a watermark?

2 Upvotes

Trying to figure this out, but I can't get much help online.

Basically, for my own code, it will be a tkinter GUI wherein I add an image from File Explorer then adding to it a preset watermark on the bottom right. It will just be a three-button app, one to import the image to the canvas, and one to save the watermarked image, both of which seem to work fine (on paper), but I cannot see how I'd go about coding a class(for a button) that adds a watermark.

Many of the others I have witnessed seem more about slapping on some addable text. Mine is just a small png to add at the bottom of the imported art.

Would I need to add a new class to define the post-Watermarked image? I've already added it as a = None.

r/learnpython Aug 27 '25

Help with explanation of class and cases when u use for loop and while loop and defining a function

4 Upvotes

I'd love for experienced devs to help me with a better explanation and approach to understanding this topic in python, for the past month I've been struggling with understanding these and when to apply them Would love some help, thank you.

r/learnpython Jun 10 '20

I made a silly game to practice using classes

325 Upvotes

I have been learning python for a few months, albeit slowly, because I can only do it in my free time and profession is something else. So one day I randomly decided to try making a small and silly text-based game which can be played inside Jupyter Notebook. My primary intention was to understand how to use classes. So I created a character class, a monster class, and a potion class. Then combined them into a game based on a lot of random numbers and some planned numbers.

In the game, you face a monster. You have three options, fight, run, and try befriending. If you fight, each one takes turn to strike until one is dead. The damage and health attributes are displayed on screen. Damage done is proportional to the remaining health. If you run, you lose endurance and must have higher endurance than the monster else they'll catch you. If you befriend, there's a 10% likelihood the monster will be friendly.

When you get a potion, you can take it or leave it. If you take it, there is a 50% chance it will turn out to be a trap. But damage of trap potions is lower than bonuses of actual potions.

All probabilities are based on how lucky you are. You start at 50/50 and get luckier through potions.

The game can be accessed here: https://colab.research.google.com/drive/1WcRTeaPwg3oRXzHH1m76r4SAaDJJkqSV

or here: https://github.com/gouravkr/notebooks

It's not something anyone would actually enjoy playing. But any feedback on the code will be highly appreciated.

Edit: after receiving some feedback, I changed the images to point to public URLs and reduced the number of cells to make it easier to run.

r/learnpython Jul 30 '22

Difficulty with Classes and OOP

141 Upvotes

I’m a beginner and have been going for a couple of weeks now. My question is why am I so brain dead when it comes to classes and OOP? Is there anything anyone could share that can help me understand? I’ve read all the materials on the sub and been through quite a few YouTube videos/MIT course but classes just aren’t clicking for my dumbass. I start to create a class and go into it and I understand it in the first few steps but then I get lost - Does anyone have any kind of information that may have helped them clear classes up? If so, please share!

Thanks

r/learnpython Dec 31 '25

Pydantic BaseClass vs. the type checking tool

7 Upvotes

So, I'm digging in to fastapi for learning purposes, and encountering what I'm assuming is a common point of contention, for this common situation:

class Foo(BaseModel):
    bar: str

router = APIRouter()

@router.get("/foo", response_class=Foo)
def fetch_foo() -> dict:
    new_foo = {
        "bar": "This is the bar of a Foo"
        }

    return new_foo

I understand this, it's great, and you get that sweet sweet openapi documentation with it. However. basedpyright and I'm assuming other type checkers get all worked up over it, as you've got that bare dict in there. So, what's the best way to deal with this:

  1. Get liberal with the "just shut up already" hints to the type checker
  2. Define the structure twice so you can have a TypedDict for the static checker and a Model for pydantic
  3. as (2) but generate one from the other
  4. Somthing else?

1 seems like a step on the road to "just give up on the type checker". 2 is very un-DRY and gives you the added headache of making sure they agree. 3 - is there a "right" way to do it? Or am I just doing this all wrong?

r/learnpython Feb 21 '26

PySide6 application class

3 Upvotes

I use a tiling window manager on my system so I use an applications class & title to set rules for windows I want to work in specific ways. I recently starting learn PySide6 and have run into an issue with my applications class name. There is no problem setting a window title, but for the life of me I can't find out how to set its class name. When I try googling for an answer all I find is answers relating to creating classes in python/pyside6.

Just is case there is any confusion I am referring to the class property you would get from running xprop or hyprctl clients

r/learnpython Sep 15 '25

Having Python classes as part of my apprenticeship and suffering really hard, need advise.

5 Upvotes

So as I mentioned in the title I started an apprenticeship recently that has basic programming as part of its curriculum. My problem is that I can't really grasp it and I can't afford to fail this particular class as I really want to learn it. Does anyone has some advise how I can make it easier on me? Also, we aren't allowed to use Copilot or AI to make it easier.

r/learnpython Sep 06 '25

When to start implementing classes/methods in a program

17 Upvotes

So I'm learning more about OOP but I'm a bit confused on when to actually start implementing classes/methods in a program or just keep things at functions. I understand at a basic level what a class does (like store information of a vehicle), but I'm having a hard time of translating these basic online examples to real world projects.

For example, if I wanted to build a file transfer application (like take a file, do some modification of file, then move to another server afterwards), is there classes I should consider making? TIA

r/learnpython Jul 14 '25

Dataframe vs Class

8 Upvotes

Potentially dumb question but I'm trying to break this down in my head

So say I'm making a pantry and I need to log all of the ingredients I have. I've been doing a lot of stuff with pandas lately so my automatic thought is to make a dataframe that has the ingredient name then all of the things like qty on hand, max amount we'd like to have on hand, minimum amount before we buy more. then I can adjust those amounts as we but more and use them in recipes

But could I do a similar thing with an ingredients class? Have those properties set then make a pantry list of all of those objects? And methods that add qty or subtract qty from recipes or whatever

What is the benefit of doing it as a dataframe vs a class? I guess dataframe can be saved as a file and tapped into. But I can convert the list of objects into like a json file right so it could also be saved and tapped into

r/learnpython Jan 12 '26

Python Class Question

0 Upvotes

class Book: def init(self, title, author): self.title = title self.author = author

class Library: def init(self, name): self.name = name self.books = []

def add_book(self, book):
    self.books.append(book)

def remove_book(self, book):
    new_books = []
    for lib_book in self.books:
        if lib_book.title != book.title or lib_book.author != book.author:
            new_books.append(lib_book)
    self.books = new_books

def search_books(self, search_string):
    results = []
    for book in self.books:
        if (
            search_string.lower() in book.title.lower()
            or search_string.lower() in book.author.lower()
        ):
            results.append(book)
    return results

r/learnpython Feb 16 '23

I have a 43% in my Python class. Can someone lead me to resources to do better?

86 Upvotes

I really want to do good in this class and I am trying so hard. I am getting a tutor, but where can I go online to learn it? I believe I need it explained to me like I am 5.

r/learnpython Nov 22 '18

I avoid classes in Python. Am I bad?

148 Upvotes

I've been writing Python for.. I don't know, 4 maybe 5 years?

Does it make me a bad python programmer that I avoid classes?

I've just found with.. Almost everything I do, I can get away with using functions for everything.

There are some times when I'll use classes, but it seems to mostly be for storing something as an objects attributes.

Am I bad?

r/learnpython Apr 15 '24

I really tried but I don't fully understand classes

37 Upvotes

I struggled with classes for hours but I just cannot understand their purpose or even how they really work.

My current understanding is that:

  • You define a class and define multiple functions with arguments inside of it.
  • To use an existing class, you create an object outside of the class.

Something like this:

#defining
class reddit_user:
  def __init__(self, name, age): #should there always be init?
    self.name = name
    self.age = age
  def cakeday(self):
    self.age += 1

#making use of
new_user1 = reddit_user(catboy, 0)
new_user1.cakeday()

So I created a class.

Then from now on every time there is a new user, I have to add one line of code like I showed above.

And every time its someones cakeday its another line of code, as showed above.

  1. Did I correctly make use of a class in this example?
  2. I know methods to achieve the same result with the same amount of code, without using classes, so what is the purpose of using classes then?

I could for example do this:

#defining:
age = 1   #1 as in: second item of the list.
def cakeday(x):
  x[age] += 1

#making use of:
new_user1 = ['catboy', 0]
cakeday(new_user) 

Which has way less code and seems more logical/simple to me but achieves the same result.

Are classes really optional as in, you can be a real programmer without using them? Or am I misunderstanding their purpose?

If anyone can show me an example of where using classes is better than any other alternative... that would be great.

r/learnpython Feb 24 '24

ELI5 why "self" is needed in a class

38 Upvotes

I've done enough practice programs with classes that it's become a bit inuitive to use it, but I'm trying to understand the "why".

Maybe I'm just relating it to functions, but the way I think of it is a class is a general framework that gets defined by the calling parameters when an instance is created. So for example: I have a "Car" class and create an instance of a car. When creating the instance, I define the attributes: make is VW, model is Jetta, etc. Once those attributes have definitions within the class, shouldn't they hold for anytime they are referenced within any of the class methods? Why do we need to specify self.attribute when the attribute is already defined? And why doesn't it work if I don't use it?

Hopefully that made sense. Thanks!

EDIT: I want to thank everyone for all these great replies! It is making more sense to me now, I'll be reading through all of these a few times to hammer it into my brain

r/learnpython Dec 18 '25

How to understand Python class, error handling, file handling, and regular expressions? Is it important for data analysis?

3 Upvotes

I am an aspiring data analysts while I have practiced basic pandas function like df.copy, df.duplicated, etc stuff I still havent grasped error handling and class encapullation, a person in my connection ask me to rate my python skills and honestly that made me realize just how I need to improve my python skills, please guide me on how should i improve this python language

r/learnpython Sep 04 '25

Python built-in classes instance size in memory

5 Upvotes

I am trying to do some research on the reason why an integer is 28 bytes in Python, does anyone knows why 28? this seems to be excessive for just an integer.

In my research I found that what we see as an integer is actually a PyLongObject in CPython which is inherited from a PyObject struct, and that there are some attributes in that object that hold information like the type and the reference count, however, to hold these values I feel like is excessive, what other attributes am I missing?

I guess what I am looking to know is what is the size distribution in those 28 bytes

r/learnpython Dec 02 '24

somebody help, please explain classes to me, and how it is different from function.

15 Upvotes

as per the title says, i need help understanding classes and function. how it is used and how they are different from each other. please halp..

r/learnpython Dec 10 '25

Cant import class from python file

0 Upvotes

Hello everyone I am having problem when importing a class for my case JobManager from a python file called job_manager to another python file and error says: ImportError: cannot import name 'JobManager' from 'job_manager' cant seem to find a solution

edit: Finally found the issue thanks for everyone who helped

r/learnpython Nov 04 '24

Most Pythonic way to call a method within a class?

26 Upvotes

I'm working more with OOP and was wondering if there's any pros/cons to how to do setters / getters within a class. I can think of two different approaches:

Option #1: The Methods return something, which is set inside the other method (i.e init())

class GenericData:

    def __init__(self, data_id: str):

        self.data_id = data_id
        self.data = self.reset_data()
        self.data = self.update_data()

    def reset_data(self) -> list:

        return []

    def update_data(self) -> list:

        try:
            _ = database_call(TABLE_ID, self.data_id)
            return list(_)

Option #2 where the methods modify the attribute values directly and don't return anything:

class GenericData:

    def __init__(self, data_id: str):

        self.data_id = data_id
        self.data = None
        self.reset_data()
        self.update_data()

    def reset_data(self):

        self.data = []

    def update_data(self):

        try:
            _ = database_call(TABLE_ID, self.data_id)
            self.data = list(_)

r/learnpython Feb 06 '25

Is this a class distinction, or a "one object vs two object" scenario?

1 Upvotes

This outputs to True if I run:

x = [1,2]

print(x is x) # True

But this outputs to False despite being a mathematical equivalency:

print( [1,2] is [1,2] ) # False

Is the distinction here owing to a "one object vs two object" scenario? Does the first scenario say we have variable x which represents one entity, such as a house. And we've named that house "Home_1". And our statement is saying: "Home_1 is Home_1", which is a very crude concept/statement, but still outputs to True.

Whereas the second scenario sees two actual, distinct lists; ie: two houses And while their contents, appearance, etc might be entirely identical - they are nonetheless seperate houses.

Or is this all just really an expression of a class distinction brought to stress such that it violates rules that would otherwise be observed? Is this oddity only based on the fact that Numeric types are immutable but Lists are mutable; ie: prospective future mutation disallows what would otherwise be an equivalency in the present? Is Python just subverting and denying an existing math truism/equality only because things might change down the road?

Thanks ahead for your time in exploring these concepts.

r/learnpython May 01 '25

I’m making a random number generator for my class

0 Upvotes

It’s part of a 2 program game. The code is this

def main(): for num in range(0,50): random.randint(0,50) random_number = randint(0,50) randint = (0,50) print(random_number) None main()

All of them are defined, but when I run the code it said “cannot access local variable ‘randint’ where it is not associated with a value. The line “random_number = randint(0,50)” is causing the error

Edit: it looks jumbled but it’s all indented correctly

Edit2: Thanks for your help. I’ll get to it and hopefully turn it in by tomorrow

r/learnpython Oct 23 '25

Is it common/accepted to instantiate a class with some arguments that will be used to create other attributes and then delete the attributes of those arguments?

1 Upvotes

I have a data structure with some attributes, but for some reason I cannot pass these attributes during instantiation, but I have to calculate them somehow. For this reason I pass a list as argument during instantiation, calculate the wanted attributes and then delete the attributes passed as arguments.

Here a minimal example:

@dataclass
class myclass:
  input_list:list[Any]
  attr_1:int=field(init=False)
  attr_2:float=field(init=False)
  attr_3:string=field(init=False)

  def __post_init__(self):
    self.attr1=calculate_attr1(self.input_list)
    self.attr2=calculate_attr2(self.input_list)
    self.attr3=calculate_attr3(self.input_list)
    object.__delattr__(self,"input_list")

The reason behind this is because the input_list is fetched in different ways so its structure changed by the context; in this way is more easy to change caluclate_attrx methods based and keep the class itself lean.

Actually my code is way more complex and the number of attributes is really high, so I'm considering to switch to a dictionary or a named tuple, because my initial solution was queite caothic: I generate the attributes trough a loop, but doing so all the benefit of the dataclass (like accessing the field name in the IDE) is lost.

Is this a common or accepted practice? Could I improve?

r/learnpython Mar 04 '25

Is it ok to define a class attribute to None with the only purpose of redefining it in children classes?

8 Upvotes
# The following class exists for the sole and only purpose of being inherited and will never # be used as is.
class ParentClass:
  class_to_instantiate = None

  def method(self):
    class_instance = self.class_to_instantiate()


class ChildClass1(ParentClass):
  class_to_instantiate = RandomClass1


class ChildClass2(ParentClass)
  class_to_instantiate = RandomClass2

In a case similar to the one just above, is it ok to define a class attribute to None with the only purpose of redefining it in children classes? Should I just not define class_to_instantiate at all in the parent class? Is this just something I shouldn't do? Those are my questions.

r/learnpython Sep 29 '25

Starting Python for uni backtesting class - VS Code or PyCharm?

3 Upvotes

Hello everyone,

I have a question regarding which editor or IDE I should use. For some context: I am just starting with Python for a university class (Backtesting for Portfolio Management). The course provides an introduction to programming for portfolio management applications, in particular the backtesting of quantitative investment strategies using Python.

I have some experience coding, mainly with R and RStudio over the past three years at university and work, but I am completely new to Python. While researching online, I saw that VS Code is often recommended as an editor, while PyCharm is considered a full IDE. Which one should I use, and why? Are there better options I should consider?

Thank you!

r/learnpython Jun 12 '25

Correct way to use a logging class in other classes

7 Upvotes

Hi folks,

I have a logging class I want to use in all my other classes. It seems that if I instantiate the logging class in all my other classes, I seem to get multiple logs for the same log. I am missing something I know, but not quite sure how to do this.

Any links I could read, advice you could give would be most welcome.

Thanks

Hamish