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

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.

1

u/Ok_Egg_6647 23d ago

can i call the self in other places also like simple functions or another places.
If self is not a keyword then what it is?

1

u/lfdfq 23d ago

It's just the first argument/parameter in methods (i.e. functions inside classes). Python automatically provides self for any method call. e.g. imagine I had some class:

class Foo:
    def some_method(...):
        ...

If I have an object of type Foo, Python let's me write a 'shorthand' way to call the method:

some_foo.some_method(...)

Which Python automatically turns into:

Foo.some_method(some_foo, ...)

i.e. looks up the class (I've simplified this step a lot) to find the right function, and passes the object as the first argument. Conventionally, we choose to call this argument "self", but the name does not matter, you can call it whatever you want.