+ 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?

14th Apr 2016, 4:40 PM
Andrés Rodríguez
Andrés Rodríguez - avatar
4 Answers
+ 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.
23rd May 2016, 3:16 PM
James Flanders
+ 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/
22nd Jun 2016, 3:41 PM
Yegor Ivashchenko
Yegor Ivashchenko - avatar
+ 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)
31st May 2016, 12:53 AM
Ashwin Umale
Ashwin Umale - avatar
Thanks guys, very useful! :)
25th Jun 2016, 1:55 PM
Andrés Rodríguez
Andrés Rodríguez - avatar