Search code examples
pythonclassobjectself

Is 'self' keyword Mandatory inside the class Methods?


I am python Begineer and i learned that first parameter inside the method should be contain some 'self' keyword but i found the following program runs without self keyword can you explain about this below is my code...

class Student(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def get_biggest_number(*age):
        result=0
        for item in age:
            if item > result:
                result= item
        return result


Sam = Student("Sam",18)
Peter = Student("Peter",20)
Karen = Student("Karen",22)
Mike = Student("Michael",21)

oldest= Student.get_biggest_number(Sam.age,Peter.age,Karen.age,Mike.age)
print (f"The oldest student is {oldest} years old.")

Solution

  • 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.