I'm stuck on Object Oriented Programming Question

Screen Link:

My Code:

my_list = my_list.append(8)
print(my_list.length)

What I expected to happen:
I expected it to print my new length from the updated my_list.
Why can’t I define the new list?

What actually happened:
Gave me an error.

AttributeError                            Traceback (most recent call last)
<ipython-input-1-e0fadc746842> in <module>
     19 
     20 my_list = my_list.append(8)
---> 21 print(my_list.length)
     22 
     23 

AttributeError: 'NoneType' object has no attribute 'length'
1 Like

Could you share your code for the 2 functions pls @laurenk9304

Here you are re-assigning my_list you don’t have to. It is in-place operation.
So code should be

my_list.append(8)
print(my_list.length)

Here they are. I’m confused as to why I can’t do my_list = my_list.append(8), because I thought it would not matter?
Thanks for your help!

my_list = MyList([1,1,2,3,5])
print(my_list.length)

my_list = my_list.append(8)
print(my_list.length)

Hi as @DishinGoyani mentioned, you do not need to reassign the variable back to itself when calling the method .length. You just need to call the method as is. Python does this for you. This article may help you. I quote:

Any time you see varname = , you’re creating a new name binding within the function’s scope. Whatever value varname was bound to before is lost within this scope .

Any time you see varname.foo() you’re calling a method on varname . The method may alter varname (e.g. list.append ). varname (or, rather, the object that varname names) may exist in more than one scope, and since it’s the same object, any changes will be visible in all scopes.

1 Like
my_list = my_list.append(4)
print(my_list)

Result:

None

This is what happens because you are re-assigning my_list as pointed by @DishinGoyani

2 Likes