Usage of self inside instance methods in Python












1















I have a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x


And then I make a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x


I understand that I can use self to separate attribute values across various instances of this class. My question is, if I create many utility variables (like x) inside a method, should I always create them using self?



Can anyone explain how the above two classes behave differently (if they do)?










share|improve this question























  • Not clear what you are asking. x in the first example is not an attribute; it's just a local variable. Unless you need a value that persists across method calls, prefer the local variable.

    – chepner
    Nov 14 '18 at 19:13











  • If you're going to use the x value in more than one method, then it should be bound to self and this initial definition of self.x should be done in the __init__ method

    – JacobIRR
    Nov 14 '18 at 19:14











  • @JacobIRR I'll use it inside just one method.

    – Brickomak
    Nov 14 '18 at 19:17






  • 1





    Using self does not create a local variable. If you want a local variable, where the value goes away at the end of the method, then use a local variable (no self). If you want an instance attribute, where the value is retained on the instance after the method finishes, then use an instance attribute (with self).

    – kindall
    Nov 14 '18 at 19:17













  • in that case, no need to use self.

    – JacobIRR
    Nov 14 '18 at 19:17
















1















I have a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x


And then I make a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x


I understand that I can use self to separate attribute values across various instances of this class. My question is, if I create many utility variables (like x) inside a method, should I always create them using self?



Can anyone explain how the above two classes behave differently (if they do)?










share|improve this question























  • Not clear what you are asking. x in the first example is not an attribute; it's just a local variable. Unless you need a value that persists across method calls, prefer the local variable.

    – chepner
    Nov 14 '18 at 19:13











  • If you're going to use the x value in more than one method, then it should be bound to self and this initial definition of self.x should be done in the __init__ method

    – JacobIRR
    Nov 14 '18 at 19:14











  • @JacobIRR I'll use it inside just one method.

    – Brickomak
    Nov 14 '18 at 19:17






  • 1





    Using self does not create a local variable. If you want a local variable, where the value goes away at the end of the method, then use a local variable (no self). If you want an instance attribute, where the value is retained on the instance after the method finishes, then use an instance attribute (with self).

    – kindall
    Nov 14 '18 at 19:17













  • in that case, no need to use self.

    – JacobIRR
    Nov 14 '18 at 19:17














1












1








1








I have a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x


And then I make a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x


I understand that I can use self to separate attribute values across various instances of this class. My question is, if I create many utility variables (like x) inside a method, should I always create them using self?



Can anyone explain how the above two classes behave differently (if they do)?










share|improve this question














I have a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x


And then I make a class like this



class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x


I understand that I can use self to separate attribute values across various instances of this class. My question is, if I create many utility variables (like x) inside a method, should I always create them using self?



Can anyone explain how the above two classes behave differently (if they do)?







python class oop object






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 19:10









BrickomakBrickomak

102




102













  • Not clear what you are asking. x in the first example is not an attribute; it's just a local variable. Unless you need a value that persists across method calls, prefer the local variable.

    – chepner
    Nov 14 '18 at 19:13











  • If you're going to use the x value in more than one method, then it should be bound to self and this initial definition of self.x should be done in the __init__ method

    – JacobIRR
    Nov 14 '18 at 19:14











  • @JacobIRR I'll use it inside just one method.

    – Brickomak
    Nov 14 '18 at 19:17






  • 1





    Using self does not create a local variable. If you want a local variable, where the value goes away at the end of the method, then use a local variable (no self). If you want an instance attribute, where the value is retained on the instance after the method finishes, then use an instance attribute (with self).

    – kindall
    Nov 14 '18 at 19:17













  • in that case, no need to use self.

    – JacobIRR
    Nov 14 '18 at 19:17



















  • Not clear what you are asking. x in the first example is not an attribute; it's just a local variable. Unless you need a value that persists across method calls, prefer the local variable.

    – chepner
    Nov 14 '18 at 19:13











  • If you're going to use the x value in more than one method, then it should be bound to self and this initial definition of self.x should be done in the __init__ method

    – JacobIRR
    Nov 14 '18 at 19:14











  • @JacobIRR I'll use it inside just one method.

    – Brickomak
    Nov 14 '18 at 19:17






  • 1





    Using self does not create a local variable. If you want a local variable, where the value goes away at the end of the method, then use a local variable (no self). If you want an instance attribute, where the value is retained on the instance after the method finishes, then use an instance attribute (with self).

    – kindall
    Nov 14 '18 at 19:17













  • in that case, no need to use self.

    – JacobIRR
    Nov 14 '18 at 19:17

















Not clear what you are asking. x in the first example is not an attribute; it's just a local variable. Unless you need a value that persists across method calls, prefer the local variable.

– chepner
Nov 14 '18 at 19:13





Not clear what you are asking. x in the first example is not an attribute; it's just a local variable. Unless you need a value that persists across method calls, prefer the local variable.

– chepner
Nov 14 '18 at 19:13













If you're going to use the x value in more than one method, then it should be bound to self and this initial definition of self.x should be done in the __init__ method

– JacobIRR
Nov 14 '18 at 19:14





If you're going to use the x value in more than one method, then it should be bound to self and this initial definition of self.x should be done in the __init__ method

– JacobIRR
Nov 14 '18 at 19:14













@JacobIRR I'll use it inside just one method.

– Brickomak
Nov 14 '18 at 19:17





@JacobIRR I'll use it inside just one method.

– Brickomak
Nov 14 '18 at 19:17




1




1





Using self does not create a local variable. If you want a local variable, where the value goes away at the end of the method, then use a local variable (no self). If you want an instance attribute, where the value is retained on the instance after the method finishes, then use an instance attribute (with self).

– kindall
Nov 14 '18 at 19:17







Using self does not create a local variable. If you want a local variable, where the value goes away at the end of the method, then use a local variable (no self). If you want an instance attribute, where the value is retained on the instance after the method finishes, then use an instance attribute (with self).

– kindall
Nov 14 '18 at 19:17















in that case, no need to use self.

– JacobIRR
Nov 14 '18 at 19:17





in that case, no need to use self.

– JacobIRR
Nov 14 '18 at 19:17












1 Answer
1






active

oldest

votes


















0














Let's see the difference between the two classes :



class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x


Let's create a Test object:



t = Test(1)


And see what we can do



t.var # 1
t.x # Raises AttributeError : no such attribute in the class
t.test() #3
t.x # Still erroring


And with your second class



class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x


Let's create a Test object:



t = Test(1)


And see what we can do



t.var # 1
t.x # Raises AttributeError : no such attribute in the class
t.test() #3
t.x # 3


So what ? Well we can see that any variables defined with self.VARNAME persist in the instance, while simple local variables, without self., dosen't.



However, if x needs to be accessible with t.x, i'd probably go for a property, like so



class Test:
def __init__(self, var):
self.var = var

@property
def x(self):
x = self.var + 2
return x

t = Test()
t.x # 3





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53307214%2fusage-of-self-inside-instance-methods-in-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Let's see the difference between the two classes :



    class Test:
    def __init__(self, var):
    self.var = var
    def test(self):
    x = self.var + 2
    return x


    Let's create a Test object:



    t = Test(1)


    And see what we can do



    t.var # 1
    t.x # Raises AttributeError : no such attribute in the class
    t.test() #3
    t.x # Still erroring


    And with your second class



    class Test:
    def __init__(self, var):
    self.var = var
    def test(self):
    self.x = self.var + 2
    return self.x


    Let's create a Test object:



    t = Test(1)


    And see what we can do



    t.var # 1
    t.x # Raises AttributeError : no such attribute in the class
    t.test() #3
    t.x # 3


    So what ? Well we can see that any variables defined with self.VARNAME persist in the instance, while simple local variables, without self., dosen't.



    However, if x needs to be accessible with t.x, i'd probably go for a property, like so



    class Test:
    def __init__(self, var):
    self.var = var

    @property
    def x(self):
    x = self.var + 2
    return x

    t = Test()
    t.x # 3





    share|improve this answer




























      0














      Let's see the difference between the two classes :



      class Test:
      def __init__(self, var):
      self.var = var
      def test(self):
      x = self.var + 2
      return x


      Let's create a Test object:



      t = Test(1)


      And see what we can do



      t.var # 1
      t.x # Raises AttributeError : no such attribute in the class
      t.test() #3
      t.x # Still erroring


      And with your second class



      class Test:
      def __init__(self, var):
      self.var = var
      def test(self):
      self.x = self.var + 2
      return self.x


      Let's create a Test object:



      t = Test(1)


      And see what we can do



      t.var # 1
      t.x # Raises AttributeError : no such attribute in the class
      t.test() #3
      t.x # 3


      So what ? Well we can see that any variables defined with self.VARNAME persist in the instance, while simple local variables, without self., dosen't.



      However, if x needs to be accessible with t.x, i'd probably go for a property, like so



      class Test:
      def __init__(self, var):
      self.var = var

      @property
      def x(self):
      x = self.var + 2
      return x

      t = Test()
      t.x # 3





      share|improve this answer


























        0












        0








        0







        Let's see the difference between the two classes :



        class Test:
        def __init__(self, var):
        self.var = var
        def test(self):
        x = self.var + 2
        return x


        Let's create a Test object:



        t = Test(1)


        And see what we can do



        t.var # 1
        t.x # Raises AttributeError : no such attribute in the class
        t.test() #3
        t.x # Still erroring


        And with your second class



        class Test:
        def __init__(self, var):
        self.var = var
        def test(self):
        self.x = self.var + 2
        return self.x


        Let's create a Test object:



        t = Test(1)


        And see what we can do



        t.var # 1
        t.x # Raises AttributeError : no such attribute in the class
        t.test() #3
        t.x # 3


        So what ? Well we can see that any variables defined with self.VARNAME persist in the instance, while simple local variables, without self., dosen't.



        However, if x needs to be accessible with t.x, i'd probably go for a property, like so



        class Test:
        def __init__(self, var):
        self.var = var

        @property
        def x(self):
        x = self.var + 2
        return x

        t = Test()
        t.x # 3





        share|improve this answer













        Let's see the difference between the two classes :



        class Test:
        def __init__(self, var):
        self.var = var
        def test(self):
        x = self.var + 2
        return x


        Let's create a Test object:



        t = Test(1)


        And see what we can do



        t.var # 1
        t.x # Raises AttributeError : no such attribute in the class
        t.test() #3
        t.x # Still erroring


        And with your second class



        class Test:
        def __init__(self, var):
        self.var = var
        def test(self):
        self.x = self.var + 2
        return self.x


        Let's create a Test object:



        t = Test(1)


        And see what we can do



        t.var # 1
        t.x # Raises AttributeError : no such attribute in the class
        t.test() #3
        t.x # 3


        So what ? Well we can see that any variables defined with self.VARNAME persist in the instance, while simple local variables, without self., dosen't.



        However, if x needs to be accessible with t.x, i'd probably go for a property, like so



        class Test:
        def __init__(self, var):
        self.var = var

        @property
        def x(self):
        x = self.var + 2
        return x

        t = Test()
        t.x # 3






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 19:17









        WayToDoorWayToDoor

        536317




        536317
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53307214%2fusage-of-self-inside-instance-methods-in-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine