I'm currently studying Python 3, so I'd like to ask you a basic question.
I don't understand why one of the codes below is executed by receiving one of the parameters self from the sum and avg methods. I know that Python needs to explicitly implement self as the first parameter, but shouldn't the actual parameter be substituted after self?
I think I'm the only one who's confused about the easy part, so I'd really appreciate it if you could answer me!
class Calculator:
def __init__(self, numberlist):
self.numberlist = numberlist
def sum(self):
result = 0
for num in self.numberlist:
result += num
return result
def avg(self):
total = self.sum()
return total / len(self.numberlist)
cal1 = Calculator([1,2,3,4,5])
print(cal1.sum())
print(cal1.avg())
The object-oriented languages that we know have my own reference as the first parameter.
If you use the ecx register for c++, and if you look at the byte code for Java, put this in the stack. In the case of Python, that's explicitly done. For example,
Calculator.avg(Calculator([1, 2, 3]))
You can invoke it as in .
So self means myself. You have to refer to properties, etc., even within the method. A method with only self is just a method with no input.
© 2024 OneMinuteCode. All rights reserved.