+2 votes
2 views
in Python by (4.1k points)
edited by

when do we use self in Python? In ruby we don't need to include this whereas in Python we have to, so it's clear it specifies an object created in some class, For instance check this,

    class myClass
        def myFunc(AT)
            @At = AT
        end
    end

But in Python I've to do this:

    class myClass:
        def myFunc(self, AT):
            self.AT = AT

 Can someone explain me this?

2 Answers

0 votes
by (46.1k points)
edited by

Check this example:

class X:
    foo
= []
q, w = X(), X()
q.foo.append(1)
w.foo
ans
: [1]

class X:
   
def __init__(self):
        self
.foo = []
q, w = X(), X()
q.foo.append(1)
w.foo
ans: []

 Hence, It's clear from above that Self refers to object itself.

Happy Learning...!!

0 votes
by (107k points)
edited by
  • The self parameter represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
  • Self keyword 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.

You can use the following video tutorials to clear all your doubts:-

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...