Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why class method must have self parameter in python?

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

I know why self is used in this code. This can take different students and make differnt attributes

student1 = Student()
student2 = Student()
...
studentn = Student()
------------------------------------

student1.name
student2.name
...
studentn.name

but I can't understand why this code below needs self parameter.

class Student:
    def study():
        print("I'm studying")


Student().study()

output

Traceback (most recent call last):
  File "C:/directory/test.py", line 12, in <module>
    Student().study()
TypeError: study() takes 0 positional arguments but 1 was given
like image 714
cavalist Avatar asked Dec 29 '25 22:12

cavalist


2 Answers

Because methods are passed the instance they're called on, regardless of if the method needs it or not.

If you don't want to need to have the parameter, make it a "static method":

class Student:
    @staticmethod
    def study():
        print("I'm studying")
like image 91
Carcigenicate Avatar answered Dec 31 '25 11:12

Carcigenicate


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

like image 31
emilaz Avatar answered Dec 31 '25 10:12

emilaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!