+ 4

Passing lists as parameters is failing somehow.

This sample code illustrates a problem. I try to pass two lists as arguments to a function. Here is the error: result = ex.Total([1,2,3], [4,5,6]) TypeError: Total() missing 1 required positional argument: 'nums2' class Example: def Total(self, nums1, nums2) -> float: sum = 0 for x in (nums1 + nums2): sum += x return x ex = Example result = ex.Total([1,2,3], [4,5,6])

5th Apr 2021, 7:25 PM
Jerry Hobby
Jerry Hobby - avatar
5 Answers
+ 4
Jerry Hobby Assuming you know the difference between static methods and instance methods, the 'self' argument signifies that the method is an instance method. If a method inside a class does not have the 'self' argument, that means it is a static method. On the second-last line, did you want to create an instance of the Example class? Because currently in your code, you assigning to `ex` the class Example. So `ex` is basically an alias for Example. As `ex` is a class and not an instance of a class, calling any method on `ex` which call it as if it is a static method, i.e., the argument to 'self' won't be passed. Hence the error 'missing 1 required positional argument'. If you wanted to create an instance of Example, you need to do `ex = Example()` Then if you call ex.Total([1, 2, 3], [4 5, 6]), there will be no error as now the 'self' argument would be passed.
5th Apr 2021, 8:17 PM
XXX
XXX - avatar
+ 3
Remove self from function Total...
5th Apr 2021, 7:34 PM
Jayakrishna 🇮🇳
+ 2
@Jayakrishna🇮🇳 I thought all functions within classes had to have "self". Your solution works. Thank you. But I'm confused about why I don't need "Self" there.
5th Apr 2021, 7:48 PM
Jerry Hobby
Jerry Hobby - avatar
+ 2
@XXX Thank you for that clarification. It is perfectly clear now. I appreciate the time you took to articulate that.
5th Apr 2021, 8:19 PM
Jerry Hobby
Jerry Hobby - avatar
0
это ерунда
7th Apr 2021, 5:54 PM
Света Моисеевских
Света Моисеевских - avatar