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
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")
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
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