Method reference in attribute before method is defined causing error












2















I don't understand why this works;



class parentClass(object):
pass

class childClass(parentClass):

def my_meth(var):
print(var)

a = {'meth': my_meth}

x = childClass.a['meth']("Helloworld")


Whilst this fails;



class parentClass(object):
pass

class childClass(parentClass):

a = {'meth': my_meth}

def my_meth(var):
print(var)

x = childClass.a['meth']("Helloworld")


It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?



Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?



Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?










share|improve this question























  • I think the problem here is that you are calling the function before defining it though you can define functions in any order.

    – BernardL
    Nov 26 '18 at 5:35






  • 1





    "Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.

    – juanpa.arrivillaga
    Nov 26 '18 at 6:20


















2















I don't understand why this works;



class parentClass(object):
pass

class childClass(parentClass):

def my_meth(var):
print(var)

a = {'meth': my_meth}

x = childClass.a['meth']("Helloworld")


Whilst this fails;



class parentClass(object):
pass

class childClass(parentClass):

a = {'meth': my_meth}

def my_meth(var):
print(var)

x = childClass.a['meth']("Helloworld")


It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?



Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?



Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?










share|improve this question























  • I think the problem here is that you are calling the function before defining it though you can define functions in any order.

    – BernardL
    Nov 26 '18 at 5:35






  • 1





    "Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.

    – juanpa.arrivillaga
    Nov 26 '18 at 6:20
















2












2








2








I don't understand why this works;



class parentClass(object):
pass

class childClass(parentClass):

def my_meth(var):
print(var)

a = {'meth': my_meth}

x = childClass.a['meth']("Helloworld")


Whilst this fails;



class parentClass(object):
pass

class childClass(parentClass):

a = {'meth': my_meth}

def my_meth(var):
print(var)

x = childClass.a['meth']("Helloworld")


It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?



Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?



Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?










share|improve this question














I don't understand why this works;



class parentClass(object):
pass

class childClass(parentClass):

def my_meth(var):
print(var)

a = {'meth': my_meth}

x = childClass.a['meth']("Helloworld")


Whilst this fails;



class parentClass(object):
pass

class childClass(parentClass):

a = {'meth': my_meth}

def my_meth(var):
print(var)

x = childClass.a['meth']("Helloworld")


It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?



Is this true? Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?



Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?







python python-3.x class attributes






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 26 '18 at 5:26









myolmyol

1,83974074




1,83974074













  • I think the problem here is that you are calling the function before defining it though you can define functions in any order.

    – BernardL
    Nov 26 '18 at 5:35






  • 1





    "Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.

    – juanpa.arrivillaga
    Nov 26 '18 at 6:20





















  • I think the problem here is that you are calling the function before defining it though you can define functions in any order.

    – BernardL
    Nov 26 '18 at 5:35






  • 1





    "Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.

    – juanpa.arrivillaga
    Nov 26 '18 at 6:20



















I think the problem here is that you are calling the function before defining it though you can define functions in any order.

– BernardL
Nov 26 '18 at 5:35





I think the problem here is that you are calling the function before defining it though you can define functions in any order.

– BernardL
Nov 26 '18 at 5:35




1




1





"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.

– juanpa.arrivillaga
Nov 26 '18 at 6:20







"Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?" because the body of functions arent executed when they are defined.

– juanpa.arrivillaga
Nov 26 '18 at 6:20














1 Answer
1






active

oldest

votes


















2















It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?




Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.




Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?




Your first example is fine. The order is not considered strange in Python.



That said, you do have potential alternatives. You could, for example, create a @classmethod to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.



class childClass(parentClass):

@classmethod
def _initialize(cls)
cls.a = {'meth': cls.my_meth}

def my_meth(var):
print(var)

childClass._initialize()


You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.




Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?




Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.



Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo() inside of a method bar, the . operator is doing an attribute lookup of the foo attribute on the self object. It's a similar idea when using cls.foo() in a classmethod.



It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.






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%2f53475170%2fmethod-reference-in-attribute-before-method-is-defined-causing-error%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









    2















    It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?




    Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.




    Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?




    Your first example is fine. The order is not considered strange in Python.



    That said, you do have potential alternatives. You could, for example, create a @classmethod to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.



    class childClass(parentClass):

    @classmethod
    def _initialize(cls)
    cls.a = {'meth': cls.my_meth}

    def my_meth(var):
    print(var)

    childClass._initialize()


    You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.




    Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?




    Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.



    Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo() inside of a method bar, the . operator is doing an attribute lookup of the foo attribute on the self object. It's a similar idea when using cls.foo() in a classmethod.



    It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.






    share|improve this answer






























      2















      It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?




      Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.




      Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?




      Your first example is fine. The order is not considered strange in Python.



      That said, you do have potential alternatives. You could, for example, create a @classmethod to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.



      class childClass(parentClass):

      @classmethod
      def _initialize(cls)
      cls.a = {'meth': cls.my_meth}

      def my_meth(var):
      print(var)

      childClass._initialize()


      You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.




      Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?




      Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.



      Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo() inside of a method bar, the . operator is doing an attribute lookup of the foo attribute on the self object. It's a similar idea when using cls.foo() in a classmethod.



      It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.






      share|improve this answer




























        2












        2








        2








        It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?




        Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.




        Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?




        Your first example is fine. The order is not considered strange in Python.



        That said, you do have potential alternatives. You could, for example, create a @classmethod to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.



        class childClass(parentClass):

        @classmethod
        def _initialize(cls)
        cls.a = {'meth': cls.my_meth}

        def my_meth(var):
        print(var)

        childClass._initialize()


        You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.




        Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?




        Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.



        Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo() inside of a method bar, the . operator is doing an attribute lookup of the foo attribute on the self object. It's a similar idea when using cls.foo() in a classmethod.



        It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.






        share|improve this answer
















        It would seem that a class is read line by line on execution and if the method definition has not been parsed before it is referenced within an attribute, an error occurs?




        Yes, that is true. Class definitions are executed from top to bottom, just like module-level code. You can even put things like if/else statements and for loops directly inside the class body.




        Is there a way to keep the class attributes at the top of the class to preserve readability and consistent layout?




        Your first example is fine. The order is not considered strange in Python.



        That said, you do have potential alternatives. You could, for example, create a @classmethod to initialize class attributes at the top of the class, and then call immediately after the class declaration, e.g.



        class childClass(parentClass):

        @classmethod
        def _initialize(cls)
        cls.a = {'meth': cls.my_meth}

        def my_meth(var):
        print(var)

        childClass._initialize()


        You could even write a class decorator to do this step for you (if you think that's prettier), as they execute after the class declaration code has completed execution.




        Why does this occur in class/static attributes whilst you can def methods in any order and reference them from other methods written above or below them?




        Executing a function definition is different from calling the function object it creates. The former just creates the function object and assigns its name to the local context. The latter runs its code.



        Classes are just fancy dicts. You can swap attributes in and out of them at runtime. When you do a self.foo() inside of a method bar, the . operator is doing an attribute lookup of the foo attribute on the self object. It's a similar idea when using cls.foo() in a classmethod.



        It's entirely possible to write a function that references an attribute that doesn't exist. It will fail with an AttributeError, of course, if you call it, but if somehow the attribute gets set later, then you can call it successfully.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 26 '18 at 6:32

























        answered Nov 26 '18 at 5:41









        gilchgilch

        3,8901716




        3,8901716






























            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%2f53475170%2fmethod-reference-in-attribute-before-method-is-defined-causing-error%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

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks