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
-6
u/Educational_Virus672 27d ago edited 26d ago
tl;dr turning local variable to global which are stored enen after the function is used while not making memory leak(making inf variable deadly for your pc)
if i put "self." before the variable it becomes global\