0

How do I add a variable number of arguments in a class method?

https://code.sololearn.com/ca123a14A10A This code works fine with just "math" and "economics" but if more subjects are added it doesn't work

23rd May 2021, 9:02 AM
Elias Kamakas
Elias Kamakas - avatar
12 Antworten
+ 2
Elias Kamakas There is no way to pass multiple objects as an argument but you can add objects in a list then you can calculate grade like this: class Subject: def __init__(self, name, grade): self.name = name self.grade = grade list = [] list.append(Subject("Math", 17)) list.append(Subject("Economics", 16)) list.append(Subject("Biology", 15)) sum = 0 for ob in list: sum += ob.grade print (sum)
23rd May 2021, 10:24 AM
A͢J
A͢J - avatar
+ 3
""" __add__ (magic) method is designed to return addition (plus operator) of two objects... in an expression with multiple additions, as a+b+c, first is computed a+b, then (a+b)+c... but your __add__ implementation print some text and return None ^^ so your implementation could look like: """ class Subject: def __init__(self,name,grade): self.name = name self.grade = grade def __add__(self,other): if isinstance(other,Subject): return self.grade + other.grade return self.grade + other def __radd__(self,other): return self.grade + other """ so now your print(a+b+c) as well as (a+(b+c)) would work as expected (or with any number of chained plus operators) ;P """
23rd May 2021, 3:30 PM
visph
visph - avatar
+ 3
visph yeah but I didn't like it. It felt wrong and crazy
23rd May 2021, 5:26 PM
Oma Falk
Oma Falk - avatar
+ 2
Elias Kamakas That's what I am trying to search if we can pass as *args or **args.
23rd May 2021, 9:28 AM
A͢J
A͢J - avatar
+ 2
visph just realized. it will go out to your solution. although one can add 3 to mathematics, what is not too nice.
23rd May 2021, 5:06 PM
Oma Falk
Oma Falk - avatar
+ 2
visph I think, this is clean code now.
23rd May 2021, 5:16 PM
Oma Falk
Oma Falk - avatar
+ 2
Frogged yes, that's another way to do, but you have changed too the way of doing the final addition output ;P
23rd May 2021, 5:24 PM
visph
visph - avatar
+ 1
Elias Kamakas Because your add function will accept only two objects. https://code.sololearn.com/c6evuSbcDc90/?ref=app
23rd May 2021, 9:15 AM
A͢J
A͢J - avatar
+ 1
🅰🅹 🅐🅝🅐🅝🅣 I see. Is there a way to make the function accept a variable number of arguments? Something like *args perhaps?
23rd May 2021, 9:27 AM
Elias Kamakas
Elias Kamakas - avatar
23rd May 2021, 5:02 PM
Oma Falk
Oma Falk - avatar
+ 1
Frogged have you tested your code? It doesn't work ^^
23rd May 2021, 5:04 PM
visph
visph - avatar
+ 1
Frogged it depends of the purpose of "adding 3 to mathematics"... but that's even nice, because you could do it if you want ^^ (if that's not expected, than that's a logical bug, as you could do a lot of other kind by coding ;P)
23rd May 2021, 5:16 PM
visph
visph - avatar