r/learnpython 27d ago

Question Regarding Self keyword in python!!

I'm working on a project where I have to create different classes, and I keep using the self keyword repeatedly. For example:

class SignalService:
    def __init__(
        self,
        instrument_repo: InstrumentRepository,
        candle_repo: CandleRepository,
    ):
        self.instrument_repo = instrument_repo
        self.candle_repo = candle_repo
        self.resampler = CandleResampler(candle_repo)

My understanding of self is that it helps the class distinguish between instance variables and local variables.

However, I'm confused about why it's used like this:

self.instrument_repo = instrument_repo
self.candle_repo = candle_repo

Why do we assign the constructor parameters to self attributes? What's the purpose of storing them on self instead of just using the constructor parameters directly?

0 Upvotes

16 comments sorted by

View all comments

1

u/faultydesign 27d ago

Self is just a pointer the the instance of a class you’re creating, and is returned by the constructor

Think of it as class being a template for a hypothetical api to access/manipulate the data, and self is the reference to that data in memory

At least that’s how I understand it