Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why always add self as first argument to class methods? [duplicate]

Possible Duplicate:
Why do you need explicitly have the “self” argument into a Python method?

I understand why self is always the first argument for class methods, this makes total sense, but if it's always the case, then why go through the hassle of typing if for every method definition? Why not make it something thats automatically done behind the scenes?

Is it for clarity or is there a situation where you may not want to pass self as the first argument?

like image 746
jonathan topf Avatar asked Oct 14 '12 12:10

jonathan topf


People also ask

Why we use self as the first argument in a method?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

Which will have the first argument named as self?

Instance methods, i.e. methods not annotated with @classmethod or @staticmethod , are expected to have at least one parameter. This parameter will reference the object instance on which the method is called. By convention, this first parameter is named "self".

What is the first argument of an instance method of a class?

Class Methods A class method is similar to an instance method, but it has a class object passed as its first argument. Recall that, when an instance method is called from an instance object, that instance object is automatically passed as the first argument to the method.

What would be the consequence of not requiring the self argument in methods?

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.


1 Answers

Because explicit is better than implicit. By making the parameter an explicit requirement, you simplify code understanding, introspection, and manipulation. It's further expanded on in the Python FAQ.

Moreover, you can define class methods (take a class instead of an instance as the first argument), and you can define static methods (do not take a 'first' argument at all):

class Foo(object):     def aninstancemethod(self):         pass      @classmethod     def aclassmethod(cls):         pass      @staticmethod     def astaticmethod():         pass 
like image 163
Martijn Pieters Avatar answered Sep 19 '22 09:09

Martijn Pieters