What is the purpose of the self
word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:
class myClass def myFunc(name) @name = name end end
Which I understand, quite easily. However in Python I need to include self
:
class myClass: def myFunc(self, name): self.name = name
Can anyone talk me through this? It is not something I've come across in my (admittedly limited) experience.
The self-definition refers to that part of self-related. knowledge that contains attributes crucial for the definition. of oneself. It involves the subjectively most important. characteristics to which individuals feel committed and.
Your self is your sense of who you are, deep down — your identity. When you let someone else know you well, you reveal your true self to them. If the subject of your thoughts is you, you're thinking about your self — or, alternately, yourself.
word forming element indicating "oneself," also "automatic," from Old English use of self (pron.) in compounds, such as selfbana "suicide," selflice "self-love, pride, vanity, egotism," selfwill "free will." Middle English had self-witte "one's own knowledge and intelligence" (early 15c.).
Self can be a noun or an adjective.
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.
.
Let's say you have a class ClassA
which contains a method methodA
defined as:
def methodA(self, arg1, arg2): # do something
and ObjectA
is an instance of this class.
Now when ObjectA.methodA(arg1, arg2)
is called, python internally converts it for you as:
ClassA.methodA(ObjectA, arg1, arg2)
The self
variable refers to the object itself.
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