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
12 Respostas
+ 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)
+ 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
"""
+ 3
visph yeah but I didn't like it. It felt wrong and crazy
+ 2
Elias Kamakas
That's what I am trying to search if we can pass as *args or **args.
+ 2
visph just realized. it will go out to your solution.
although one can add 3 to mathematics, what is not too nice.
+ 2
visph I think, this is clean code now.
+ 2
Frogged yes, that's another way to do, but you have changed too the way of doing the final addition output ;P
+ 1
Elias Kamakas
Because your add function will accept only two objects.
https://code.sololearn.com/c6evuSbcDc90/?ref=app
+ 1
đ
°đ
č đ
đ
đ
đ
đ
Ł I see. Is there a way to make the function accept a variable number of arguments? Something like *args perhaps?
+ 1
Frogged have you tested your code? It doesn't work ^^
+ 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)