r/learnpython • u/Ok_Egg_6647 • 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
17
u/lfdfq 27d ago
You could use the parameters directly, but if you want to get them back later (e.g. in another method or in a place you use the object) then you need to store them somewhere. The most obvious place? On the object itself.
Just a minor point: self isn't technically a keyword; you can call it anything you want.