4

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.")
Saleem Ali
  • 1,363
  • 11
  • 21
dinadis
  • 79
  • 1
  • 10
  • 4
    First things first, `self` is not a reserved keyword in python, but a strong convention. – Sayandip Dutta Oct 17 '19 at 07:07
  • seems to be a duplicate of https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python – jtwilson Oct 17 '19 at 07:12
  • Possible duplicate of [What is the purpose of the word 'self', in Python?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python) – Saleem Ali Oct 17 '19 at 07:13
  • this is not exact duplicate but i mean 'self' is mandatory inside the class methods. – dinadis Oct 17 '19 at 07:32
  • did you actually read what we posted? your exact question is answered several times in that thread. – jtwilson Oct 17 '19 at 15:56
  • thanks i was not actually clear on concept of decoraters, static method,class method so I got the above problem of 'self ' – dinadis Oct 18 '19 at 05:59

4 Answers4

1

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.

1

You shouldn't mistake classmethod with instance methods. In python you can declare a method inside a class as classmethod. This method takes a reference to the class as the first argument.

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

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

    @classmethod
    def get_classname(cls):
        # Has only access to class bound items
        # gets the class as argument to access the class
        return cls.__name__

    @staticmethod
    def print_foo():
        # has not a reference to class or instance
        print('foo')
Frank
  • 1,959
  • 12
  • 27
1

self in python refers to the instance of the class that is created. Something like this in C# and Java. However there's some differences but in short: when you don't use self as input of a method, actually you're saying that this method does not need any instance, that means this method is a static method and will never use any of class attributes.

In your example we can call get_biggest_number method with not even one instance, for example you can call this method just like this:

Student.get_biggest_number(20,30,43,32)

and the output will be 43.

Hamidreza
  • 1,465
  • 12
  • 31
0

The self keyword is used to represent an instance (object) of the given class. ... However, since the class is just a blueprint, self allows access to the attributes and methods of each object in python.

class ClassA:

    def methodA(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

let say ObjectA is an instance of the class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself and the code becomes as:

class ClassA:

    def methodA(ObjectA, arg1, arg2):
        ObjectA.arg1 = arg1
        ObjectA.arg2 = arg2
Rasheed Ahmad
  • 51
  • 1
  • 6