+ 2
Why do I have to write "self" in each method definition, if later I won't use any argument?
Does it have a good reason?
4 Respuestas
+ 7
Python doesn't force you on using "self". You can give it whatever name you want. You just have to remember that the first argument in a method definition header is a reference to the object.
The usage is based on the Zen of Python, which states "Explicit is better than implicit." Python elects to make things like this explicit rather than based on a rule.
+ 5
when you write obj = SomeClass(); obj.some_method() What actually is going on under cover is this: SomeClass.some_method(obj). That's why any method needs at least one parameter to refer to the object it was called on. Check out this code snippet: http://www.sololearn.com/app/JUMP_LINK__&&__python__&&__JUMP_LINK/playground/ch1SZOVp1b6R/
+ 3
'self' acts synonymous to the word with which we will associate this class. So, when you assign this class to the word 'sam'... the word 'self' will be replaced by 'sam' everywhere.
We use 'self' which describing the class to denote the name of the attribute and the way in which the particular attribute will be called (in this case I want to call it as 'Sam.dog.colour' , so l will name the attribute as 'self.dog.colour' to denote the way the attribute will be called)
0
Thanks guys, very useful! :)