So I just started programming in python and I don't understand the whole reasoning behind 'self'. I understand that it is used almost like a global variable, so that data can be passed between different methods in the class. I don't understand why you need to use it when your calling another method in the same class. If I am already in that class, why do I have to tell it??
example, if I have: Why do I need self.thing()?
class bla: def hello(self): self.thing() def thing(self): print "hello"
Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The short answer is "because you can def thing(args) as a global function, or as a method of another class.
self is the first method of every Python class Some programming languages use the word this to represent that instance, but in Python we use the word self . When you define a class in Python, every method that you define, must accept that instance as its first argument (called self by convention).
If there was no self argument, the same class couldn't hold the information for both these objects. However, since the class is just a blueprint, self allows access to the attributes and methods of each object in python. This allows each object to have its own attributes and methods.
Also you can make methods in class static
so no need for self
. However, use this if you really need that.
Yours:
class bla: def hello(self): self.thing() def thing(self): print "hello"
static edition:
class bla: @staticmethod def hello(): bla.thing() @staticmethod def thing(): print "hello"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With