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?
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.
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".
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.
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.
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
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