11/18 Can someone explained it? Please


#1

Hello guys, here is the code it worked.
n = [3, 5, 7]
def list_extender(lst):
lst.append(9)
return lst

print list_extender(n)
My question is why I got wrong when I wrote list_extender.append(9) instead of lst.append(9)?
I would deeply appreciate any explanation. Thanks


#2

@husmyat94

Simply put, you are trying to use a method that the function did not have. Also functions do not have methods, classes have methods.

Example:

class ListExtender(object):
    def __init__(self, lst):
        self.lst = lst
    def extend_list(self, *args, **kwargs):
        for arg in args:
            self.lst.append(arg)
        for karg in kwargs:
            self.lst.append(karg)
    def __str__(self):
        return str(self.lst)

lst = ListExtender(['a', 'b', 'c'])
lst.extend_list(['d', 'e', 'f'])
print(lst)
lst.extend_list('g', 'h', 'i')
print(lst)

Now from my code here you can see I create a class and give it a method that extends the list. I also overrode the __str__ method for it so that it would return a str of it's lst property.

Easy enough? Now remember that functions do not have methods at all, if you want to work on data returned by one function in another you can do that.

Example:

a = 5
b = sum(a * sum(a * sum(a * 3))) # Working on the result of a function is easy

If you still do not get what's going on feel free to ask.


#3

@zeziba Thanks a lot.