Why do you add self when calling a function?

Asked 2 years ago, Updated 2 years ago, 133 views

def sum(self):
        resurt = 0
        for num in self.numberlist:

               resurt += num
        return resurt

def avg(self):
       total = self.sum()
       return total/ len(self.numberlist)

Medium total = self.Why is self in sum()?

python class

2022-09-22 17:55

2 Answers

Python is full of linguistically imperfect things.

Object orientation is at the prototype level, and there are no essential properties such as encapsulation (name mangling level support), and constants.

Self is one of them.

By default, object-oriented languages have this pointer. However, it is implicitly hidden and this is delivered at the beginning of every method.

But Python made it explicit. In Python, if there is no self, it becomes a class method. In summary, you must have self to access variables, etc. for that object.

In other words, if you make an instance method, memorize it by saying that you have to add self.


2022-09-22 17:55

The rules of another language seem strange because you are familiar with one language.

When you get used to languages like Python, you may feel more anxious to call a function without belonging. Rather, if you explicitly specify the belonging of a function, it becomes more readable.

When you get used to this, some teams make it a rule to mark this->sum() using this, which you don't even have to use in a language like C++.


2022-09-22 17:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.