Reputation: 125
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
Upvotes: 2
Views: 9462
Reputation: 852
The reason is because whenever a method is called on an object, Python automatically passes the method the object that called it.
Upvotes: 0
Reputation: 1
Guido Van Rossum (the maker of python) wrote a blogpost in which he told why explicit self has to stay.
Upvotes: 0
Reputation: 909
Self is not a keyword, It's just a convention. Also, when you pass self to the method of a class you are referring to that particular object by using self(as a class can have multiple objects and all have access to that method), self gives you the option to use the attributes of the class in that method by using self.att . You can make the output of the function study as attribute like self.study="I am studying" that will better suit your purpose. You can read more here and here .
Upvotes: 0
Reputation: 2806
When creating function inside a class you need to pass self
as argument:
class Student:
def study(self):
print("I'm studying")
Upvotes: -2
Reputation: 21
you can use this code if not add 'self'
class Student:
def study():
print("I'm studying")
Student.study()
output: I'm studying
Upvotes: 2
Reputation: 6324
This is just how python works when you do instance.method(). Method receives the instance as the first parameter. Note that:
Student().study()
is equivalent to
student = Student()
student.study()
Upvotes: 0
Reputation: 45741
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")
Upvotes: 5
Reputation: 2062
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
Upvotes: 3