In this example code:
class new: def __init__(self, list): self.list = list def math(self): average = sum(self.list)/len(self.list) total = sum(self.list) return len(self.list) def values(self): return self.list list = new([1,2,3,4])
is there a way to call the average and total variables in the math method without putting it in the return function (I want the math function to only return the length of the list)? I tried this:
list.math().average
but this gives an error. I want to be able to call the variables in one line. Any suggestions?
Advertisement
Answer
You can put them in instance attributes.
class new: def __init__(self, l): self.list = l def math(self): self.average = sum(self.list)/len(self.list) self.total = sum(self.list) return len(self.list) def values(self): return self.list mylist = new([1,2,3,4]) mylist.math() print(mylist.average, mylist.total)
BTW, don’t use list
as a variable name, it replaces the built-in function with that name.