Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
3 views
in Python by (4k 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 (46k 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 (106k 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

0 votes
1 answer
asked Jun 27, 2019 in Python by Sammy (47.6k points)
0 votes
4 answers
0 votes
4 answers
0 votes
4 answers
asked Apr 1, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer

Browse Categories

...