Attribute created in one method doesn't exist in other method












11















Here I have an attribute 'a', which is defined in first class method and should be changed in second.
When calling them in order, this message appears:




AttributeError: 'Class' object has no attribute 'a'




The only way I've found - define 'a' again in second method, but in real code it has long inheritance and app will be messed.
Why doesn't it work? Isn't self.a equal to Class.a?



class Class(object):
def method_1(self):
self.a = 1
def method_2(self):
self.a += 1

Class().method_1()
Class().method_2()









share|improve this question





























    11















    Here I have an attribute 'a', which is defined in first class method and should be changed in second.
    When calling them in order, this message appears:




    AttributeError: 'Class' object has no attribute 'a'




    The only way I've found - define 'a' again in second method, but in real code it has long inheritance and app will be messed.
    Why doesn't it work? Isn't self.a equal to Class.a?



    class Class(object):
    def method_1(self):
    self.a = 1
    def method_2(self):
    self.a += 1

    Class().method_1()
    Class().method_2()









    share|improve this question



























      11












      11








      11


      1






      Here I have an attribute 'a', which is defined in first class method and should be changed in second.
      When calling them in order, this message appears:




      AttributeError: 'Class' object has no attribute 'a'




      The only way I've found - define 'a' again in second method, but in real code it has long inheritance and app will be messed.
      Why doesn't it work? Isn't self.a equal to Class.a?



      class Class(object):
      def method_1(self):
      self.a = 1
      def method_2(self):
      self.a += 1

      Class().method_1()
      Class().method_2()









      share|improve this question
















      Here I have an attribute 'a', which is defined in first class method and should be changed in second.
      When calling them in order, this message appears:




      AttributeError: 'Class' object has no attribute 'a'




      The only way I've found - define 'a' again in second method, but in real code it has long inheritance and app will be messed.
      Why doesn't it work? Isn't self.a equal to Class.a?



      class Class(object):
      def method_1(self):
      self.a = 1
      def method_2(self):
      self.a += 1

      Class().method_1()
      Class().method_2()






      python class attributes






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 18 '18 at 15:37









      Aran-Fey

      20.9k53470




      20.9k53470










      asked Apr 22 '13 at 23:57









      user2309239user2309239

      58114




      58114
























          2 Answers
          2






          active

          oldest

          votes


















          14














          Short answer, no. The problem with your code is that each time you create a new instance.



          Edit: As abarnert mentions below, there is a big difference between Class.a and c.a. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's comment below or the discussion here for more info.



          Your code is equivalent to



          c1 = Class()
          c1.method_1() # defines c1.a (an instance attribute)
          c2 = Class()
          c2.method_2() # c2.a undefined (the c2 instance doesn't have the attribute)


          You probably want to do somthing like



          c = Class()
          c.method_1() # c.a = 1
          c.method_2() # c.a = 2
          print "c.a is %d" % c.a # prints "c.a is 2"


          Or probably even better would be to initialize c with an a attribute



          class Class:
          def __init__(self):
          self.a = 1 # all instances will have their own a attribute





          share|improve this answer





















          • 9





            Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

            – abarnert
            Apr 23 '13 at 0:19



















          3














          A newly-created instance of Class has no attribute a when you do instance_of_class.method_2() without calling method_1, as in your example.



          Consider this slightly altered version of your code:



          class CreateNewClassInstance(object):
          def create_a(self):
          self.a = 1
          def add_one_to_a(self):
          self.a += 1

          CreateNewClassInstance().create_a()
          CreateNewClassInstance().add_one_to_a()


          Each time you call Class() (or CreateNewClassInstance()) you create a new object, with its own attribute a. Until you initialize a, you don't have an attribute with that name.



          Most of the time this isn't an issue - however, += will attempt to load self.a before adding one to it - which is what is causing your AttributeError in this case.






          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%2f16158684%2fattribute-created-in-one-method-doesnt-exist-in-other-method%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            14














            Short answer, no. The problem with your code is that each time you create a new instance.



            Edit: As abarnert mentions below, there is a big difference between Class.a and c.a. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's comment below or the discussion here for more info.



            Your code is equivalent to



            c1 = Class()
            c1.method_1() # defines c1.a (an instance attribute)
            c2 = Class()
            c2.method_2() # c2.a undefined (the c2 instance doesn't have the attribute)


            You probably want to do somthing like



            c = Class()
            c.method_1() # c.a = 1
            c.method_2() # c.a = 2
            print "c.a is %d" % c.a # prints "c.a is 2"


            Or probably even better would be to initialize c with an a attribute



            class Class:
            def __init__(self):
            self.a = 1 # all instances will have their own a attribute





            share|improve this answer





















            • 9





              Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

              – abarnert
              Apr 23 '13 at 0:19
















            14














            Short answer, no. The problem with your code is that each time you create a new instance.



            Edit: As abarnert mentions below, there is a big difference between Class.a and c.a. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's comment below or the discussion here for more info.



            Your code is equivalent to



            c1 = Class()
            c1.method_1() # defines c1.a (an instance attribute)
            c2 = Class()
            c2.method_2() # c2.a undefined (the c2 instance doesn't have the attribute)


            You probably want to do somthing like



            c = Class()
            c.method_1() # c.a = 1
            c.method_2() # c.a = 2
            print "c.a is %d" % c.a # prints "c.a is 2"


            Or probably even better would be to initialize c with an a attribute



            class Class:
            def __init__(self):
            self.a = 1 # all instances will have their own a attribute





            share|improve this answer





















            • 9





              Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

              – abarnert
              Apr 23 '13 at 0:19














            14












            14








            14







            Short answer, no. The problem with your code is that each time you create a new instance.



            Edit: As abarnert mentions below, there is a big difference between Class.a and c.a. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's comment below or the discussion here for more info.



            Your code is equivalent to



            c1 = Class()
            c1.method_1() # defines c1.a (an instance attribute)
            c2 = Class()
            c2.method_2() # c2.a undefined (the c2 instance doesn't have the attribute)


            You probably want to do somthing like



            c = Class()
            c.method_1() # c.a = 1
            c.method_2() # c.a = 2
            print "c.a is %d" % c.a # prints "c.a is 2"


            Or probably even better would be to initialize c with an a attribute



            class Class:
            def __init__(self):
            self.a = 1 # all instances will have their own a attribute





            share|improve this answer















            Short answer, no. The problem with your code is that each time you create a new instance.



            Edit: As abarnert mentions below, there is a big difference between Class.a and c.a. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's comment below or the discussion here for more info.



            Your code is equivalent to



            c1 = Class()
            c1.method_1() # defines c1.a (an instance attribute)
            c2 = Class()
            c2.method_2() # c2.a undefined (the c2 instance doesn't have the attribute)


            You probably want to do somthing like



            c = Class()
            c.method_1() # c.a = 1
            c.method_2() # c.a = 2
            print "c.a is %d" % c.a # prints "c.a is 2"


            Or probably even better would be to initialize c with an a attribute



            class Class:
            def __init__(self):
            self.a = 1 # all instances will have their own a attribute






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 23 '17 at 12:10









            Community

            11




            11










            answered Apr 23 '13 at 0:01









            FelipeFelipe

            1,76711433




            1,76711433








            • 9





              Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

              – abarnert
              Apr 23 '13 at 0:19














            • 9





              Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

              – abarnert
              Apr 23 '13 at 0:19








            9




            9





            Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

            – abarnert
            Apr 23 '13 at 0:19





            Great answer… but it's probably worth explaining that self.a is not equal to Class.a, instead of just flatly saying "no"). self.a is an instance attribute: each Class instance has its own copy. Class.a is a class attribute: the class itself has a single copy, no matter how many instances there are (sort of like a static member in C++ and related languages). And If you don't know why you'd want a class attribute, you don't want one.

            – abarnert
            Apr 23 '13 at 0:19













            3














            A newly-created instance of Class has no attribute a when you do instance_of_class.method_2() without calling method_1, as in your example.



            Consider this slightly altered version of your code:



            class CreateNewClassInstance(object):
            def create_a(self):
            self.a = 1
            def add_one_to_a(self):
            self.a += 1

            CreateNewClassInstance().create_a()
            CreateNewClassInstance().add_one_to_a()


            Each time you call Class() (or CreateNewClassInstance()) you create a new object, with its own attribute a. Until you initialize a, you don't have an attribute with that name.



            Most of the time this isn't an issue - however, += will attempt to load self.a before adding one to it - which is what is causing your AttributeError in this case.






            share|improve this answer




























              3














              A newly-created instance of Class has no attribute a when you do instance_of_class.method_2() without calling method_1, as in your example.



              Consider this slightly altered version of your code:



              class CreateNewClassInstance(object):
              def create_a(self):
              self.a = 1
              def add_one_to_a(self):
              self.a += 1

              CreateNewClassInstance().create_a()
              CreateNewClassInstance().add_one_to_a()


              Each time you call Class() (or CreateNewClassInstance()) you create a new object, with its own attribute a. Until you initialize a, you don't have an attribute with that name.



              Most of the time this isn't an issue - however, += will attempt to load self.a before adding one to it - which is what is causing your AttributeError in this case.






              share|improve this answer


























                3












                3








                3







                A newly-created instance of Class has no attribute a when you do instance_of_class.method_2() without calling method_1, as in your example.



                Consider this slightly altered version of your code:



                class CreateNewClassInstance(object):
                def create_a(self):
                self.a = 1
                def add_one_to_a(self):
                self.a += 1

                CreateNewClassInstance().create_a()
                CreateNewClassInstance().add_one_to_a()


                Each time you call Class() (or CreateNewClassInstance()) you create a new object, with its own attribute a. Until you initialize a, you don't have an attribute with that name.



                Most of the time this isn't an issue - however, += will attempt to load self.a before adding one to it - which is what is causing your AttributeError in this case.






                share|improve this answer













                A newly-created instance of Class has no attribute a when you do instance_of_class.method_2() without calling method_1, as in your example.



                Consider this slightly altered version of your code:



                class CreateNewClassInstance(object):
                def create_a(self):
                self.a = 1
                def add_one_to_a(self):
                self.a += 1

                CreateNewClassInstance().create_a()
                CreateNewClassInstance().add_one_to_a()


                Each time you call Class() (or CreateNewClassInstance()) you create a new object, with its own attribute a. Until you initialize a, you don't have an attribute with that name.



                Most of the time this isn't an issue - however, += will attempt to load self.a before adding one to it - which is what is causing your AttributeError in this case.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 23 '13 at 0:01









                Sean VieiraSean Vieira

                114k24226230




                114k24226230






























                    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%2f16158684%2fattribute-created-in-one-method-doesnt-exist-in-other-method%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

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas