What is the `self` parameter in class methods?
The reason you need to use self.
is because Python does not use the @
syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self
is the convention, and people will generally frown at you when you use something else.) self
is not special to the code, it's just another object.
Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self.
.
Why class method must have self parameter in python?
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
Is 'self' keyword Mandatory inside the class Methods?
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.
Class methods redefining, 'self' argument problems
It's a subtlety of what .
does in Python. It both looks up the method on the class, and binds the method to the instance. This binding is what provides the class instance implicitly as the first argument, self
. Look at this:
>>> print(example.some_method)
<function my_print at 0x7f66c4129f30>
>>> print(a.some_method)
<bound method my_print of <test.example object at 0x7f66c41c2290>>
However, when the method is found on the instance (which shadows the one on the class), the binding does not happen:
>>> a = example()
my print is called
>>> a.some_method = my_print
>>> print(a.some_method)
<function my_print at 0x7f66c4129f30>
This is stated in the Python reference:
It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.
The solution, then, is to make sure that the method is always an attribute of the class instance, and call it accordingly:
class example():
def __init__(self):
self.some_method = my_print
self.some_method(self)
def test(self):
self.some_method(self)
Looks weird, works great.
If you want the method to always be an attribute of the class instead, consider using inheritance.
Why do you need explicitly have the self argument in a Python method?
I like to quote Peters' Zen of Python. "Explicit is better than implicit."
In Java and C++, 'this.
' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.
Python elects to make things like this explicit rather than based on a rule.
Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__
, self.__dict__
and other "internal" structures are available in an obvious way.
Related Topics
Change Default Python Version from 2.4 to 2.6
How to Pass a Variable by Reference
Are Dictionaries Ordered in Python 3.6+
How to Iterate Over a List in Chunks
How to Parse Xml and Get Instances of a Particular Node Attribute
How to Put the Legend Outside the Plot
Tkinter Creating Buttons in For Loop Passing Command Arguments
Convert Pandas Column to Datetime
Get a List of Numbers as Input from the User
How to Find All Occurrences of a Substring
How to Use Export With Python on Linux
How to Deal With Settingwithcopywarning in Pandas
How to Read a File Line-By-Line into a List
How to Dynamically Create Variables
Flattening a Shallow List in Python
How to Type Hint a Method With the Type of the Enclosing Class
Python, Unicode, and the Windows Console
How to Remove Accents (Normalize) in a Python Unicode String