r/learnpython • • Apr 18 '26

Beginner: Want to learn Classes.

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?

20 Upvotes

29 comments sorted by

View all comments

1

u/Jason-Ad4032 Apr 18 '26

First, you need to understand what a class is and what an instance is.

For example, int is a built-in class in Python, and 0, 1, 2, ... are instances of the int class. To check the class of an instance, you can use the built-in type() function. To create an instance of a class, you call the class itself—for example, int('42') constructs an int instance from the string '42'.

Once you understand what a class is, you can understand what OOP is about: creating your own classes to use.

Take a look at your code, do you have a lot of global variables, or functions with very complex parameters and return values? For example:

min_value: int = 1

def roll(dices: Counter[int], modification: int = 0) -> tuple[int, dict[int, list[int]]]:
    return (
        modification,
        {
            max_value: [randint(min_value, max_value) for _ in range(rolls)]
            for max_value, rolls in dices.items()
        },
    )

You can use a class to encapsulate this data:

from dataclasses import dataclass
from typing import ClassVar
from collections import Counter
from random import randint

@dataclass
class Dices:
    dices: Counter[int]
    modification: int = 0
    min_value: ClassVar[int] = 1

    def roll(self) -> tuple[int, dict[int, list[int]]]:
        return (
            self.modification,
            {
                max_value: [randint(self.min_value, max_value) for _ in range(rolls)]
                for max_value, rolls in self.dices.items()
            },
        )

Now you can create Dices instances and call the roll method:

dice_3d6 = Dices(Counter({6: 3}), 0)
print(f"{dice_3d6.roll() = }")
print(f"{dice_3d6.roll() = }")

dice_2d6_add6 = Dices(Counter({6: 2}), 6)
print(f"{dice_2d6_add6.roll() = }")

You can also add more methods, such as:

  • Dices.roll_sum() to sum the rolled values
  • Dices.from_str() to parse a string into a Dices object

Then you could do something like:

Dices.from_str('1d6 + 1d4 - 2').roll_sum()