Search code examples
pythonundefined-variable

Trying to use the return value from one function in another but getting undefined variable instead


I have this code:

class Pet(object):

    def __init__(self,name=""):
        self.name = name 
        self.kind = "Unknown"
        self.toys = []  
    def add_toys(self,toys):
        new_list = []
        for toy in self.toys:
            if toy not in new_list:
                new_list.append(toy)   
        return new_list
    def __str__(self):
        toys_list = add_toys(self,toys)  
        if self.toys == []:
            return "{} is a {} that has no toys".format(self.name,self.kind)
        else:
            return "{} is a {} that has the following toys: {}".format(self.name,self.kind,toys_list)     

In the function add_toys() I have the return value new_list. I want to use that return value in the function __ str__ and define it as toys_list. However, when I write toys_list = add_toys(self, toys) it says that:

add_toys is an undefined variable


Solution

  • Your add_toys method isn't good, you're not using the toys parameters and it shouldn't return anything, it should be like

    class Pet:
        # __init__ is OK
    
        def add_toys(self, *toys):
            for toy in toys:
                if toy not in self.toys:
                    self.toys.append(toy)
    
        def __str__(self):
            if not self.toys:
                return "{} is a {} that has no toys".format(self.name, self.kind)
            else:
                return "{} is a {} that has the following toys: {}".format(self.name, self.kind, self.toys)
    

    Use like

    p = Pet("Foo")
    p.add_toys("ball")
    p.add_toys("plate", "frisbee")
    print(p) # Foo is a Unknown that has the following toys: ['ball', 'plate', 'frisbee']
    

    You could use directly a set

    class Pet:
    
        def __init__(self, name, kind="Unknown"):
            self.name = name
            self.kind = kind
            self.toys = set()
    
        def add_toys(self, *toys):
            self.toys.update(toys)