Why Do You Need Explicitly Have the "Self" Argument in a Python Method

Why do you need explicitly have the self argument in a Python method?

I like to quote Peters' Zen of Python. "Explicit is better than implicit."

In Java and C++, 'this.' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.

Python elects to make things like this explicit rather than based on a rule.

Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__, self.__dict__ and other "internal" structures are available in an obvious way.

What is the purpose of the `self` parameter? Why is it needed?

The reason you need to use self. is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.

Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..

Why class method must have self parameter in python?

The first argument of every class method, including init, is always a
reference to the current instance of the class. By convention, this
argument is always named self. In the init method, self refers to the
newly created object; in other class methods, it refers to the
instance whose method was called

More on the self variable here

python def Method should have self as first argument

Not sure if the fib / fib2 is the class method.

if they are, you may add self in the object parameter, as

def fib(self, n)

Then you may call the method like:

f = Fibonacci()
f.fib(5)

The self parameter is referring to the class object, so that you may use self attributes in the class method, in you case, you may have

def fib(self, n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
print(self.title)

Is 'self' keyword Mandatory inside the class Methods?

Code you've posted has indentation errors within it, you should first indent methods and it's content, meaning that, methods are within class. On the other hand, self refers to instance, which calls specific method and gives access to the all instance data. For example

student1 = Student('name1', 20)
student2 = Student('name2', 21)
student1.some_method(arg1)

in the last call, behind the scenes student1 is passed for self parameter of the method, meaning that all student1's data is available through self argument.

What you are trying is to use staticmethod, which has no data of the instance and is aimed to logically group class related functions without explicit instance, which does not require self in method definition:

class Student:
...
@staticmethod
def get_biggest_number(*ages):
# do the task here

On the other hand, if you would like to track all student instances and apply get_biggest_number method automatically work on them, you just have to define class variable (rather than instance variable) and on each instance __init__ append new instance to that list:

class Student:
instances = list() # class variable
def __init__(self, name, age):
# do the task
Student.instances.append(self) # in this case self is the newly created instance

and in get_biggest_number method you just loop through Student.instances list which will contain Student instance and you can access instance.age instance variable:

@staticmethod
def get_biggest_number():
for student_instance in Student.instances:
student_instance.age # will give you age of the instance

Hope this helps.

Why always add self as first argument to class 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


Related Topics



Leave a reply



Submit