Home > Back-end >  Basic Python Classes - Self Function Not Working
Basic Python Classes - Self Function Not Working

Time:09-15

I have been learning python for around a week and am trying to set up a basic LRU Cache.

I think I don't fully understand when to use the self command in OOP.

A simplified version of my code is here:

class LRUCache:
    def __init__(self):
        self.cache=[]
    
    def add_to_cache(self, cache, item_to_add):
      pass
    
my_cache = LRUCache()

while True:
     what_to_add = input("What do you want to add?")
     my_cache.add_to_cache(self.cache, what_to_add)

I get an error on the self.cache in the last line, "undefined name self"

I'm not quite sure why I get this- to my understanding my_cache is my object and it should be able to recognize self.cache, and uses that attribute within the add_to_cache function.

I tried searching around both here and on google, but was not able to specifically find what I did wrong.

I appreciate anyone's help or clarity on this situation. I am a beginner and still trying to learn. Thank you!

CodePudding user response:

self represent the current object on which your invoking the method

if you write my_cache.add_to_cache(self.cache, what_to_add)

my_cache gets "transposed" to the self argument in your def add_to_cache(self, cache, item_to_add):

imagine having a function, def test(self): print(self.name) doing my_object.test() correspond to putting my_object instead of self, same as doing test(my_object)

and then it would call my_object.name in your case you either want to do

my_cache.add_to_cache(my_cache.cache, what_to_add)

or better, since you have self, just delete the cache argument and in your function use it like that

def add_to_cache(self, item_to_add):
      cache = self.cache

and you would call it like that

my_cache.add_to_cache(what_to_add)

hope that was clear

CodePudding user response:

In python self use for the simmilar purpouse this keyword use in java.Therefore in this case self.cach indicate that cache list belong to the my_cache object. Therefore in this way you can not access cache list outside of class because python not which object you are refering.You have to move this add_to_cache method to inside of the class. Then it may be look like this.

class LRU_cache:
    def add_to_cache(self,what_to_add):
       self.cache.add(what_to_add)

Then you can call this method refering the my_cache object.

my_cache.add_to_cache(what_to_add)
  • Related