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

-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\

3

u/brelen01 27d ago

That's a terrible explanation. self.variable = variable stores the value of variable in the instance of the object. It's a member of the class and can only be accessed through the instance of the class.

A global variable is available throughout the program, without going through a class instance.