How to iterate through attributes of an object defined by getters or @property?How to sort a list of objects based on an attribute of the objects?How to know if an object has an attribute in PythonHow do I loop through or enumerate a JavaScript object?Iterate through a HashMapHow to iterate through two lists in parallel?In Python, how do I determine if an object is iterable?Using @property versus getters and settersIterate through object propertiesHow to iterate over rows in a DataFrame in Pandas?python decorator for class methods

I want light controlled by one switch, not two

Satellite in orbit in front of and behind the Moon

Project Euler # 25 The 1000 digit Fibonacci index

Why would word of Princess Leia's capture generate sympathy for the Rebellion in the Senate?

Inside Out and Back to Front

ESTA Travel not Authorized. Accepted twice before!

Nilpotent elements of Lie algebra and unipotent groups

Improving an O(N^2) function (all entities iterating over all other entities)

Can two waves interfere head on?

What's the difference between 1kb(64x16) and 1kb(128x8) for EEPROM memory size?

How does the Gameboy's memory bank switching work?

Is it possible to have a career in SciComp without contributing to arms research?

Why does airflow separate from the wing during stall?

The most secure way to handle someone forgetting to verify their account?

What does a Nintendo Game Boy do when turned on without a game cartridge inserted?

What is the difference between uniform velocity and constant velocity?

Will a ThunderBolt 3 (USB-C?) to ThunderBolt 2 cable allow me to use a MacBook Pro as second monitor?

Counting multiples of 3 up to a given number

why neutral does not shock. how can a neutral be neutral in ac current?

Does a hash function have a Upper bound on input length?

Remove side menu(right side) from finder

Three Subway Escalators

Father as an heir

Animating the result of numerical integration



How to iterate through attributes of an object defined by getters or @property?


How to sort a list of objects based on an attribute of the objects?How to know if an object has an attribute in PythonHow do I loop through or enumerate a JavaScript object?Iterate through a HashMapHow to iterate through two lists in parallel?In Python, how do I determine if an object is iterable?Using @property versus getters and settersIterate through object propertiesHow to iterate over rows in a DataFrame in Pandas?python decorator for class methods






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I know how to iterate through the attributes of an object. But that excludes attributes realized through getters/setters or @property decorators.



How can I iterate through those?



class MyClass:

def __init__(self):
self.foo = "bar"

@property
def myprop(self):
return "hello"


my_instance = MyClass()

for i in my_instance.__dict__:
print("object has attribute %s" % i)


This little script prints:



object has attribute foo


What I want though is a script that prints:



object has attribute foo
object has attribute myprop









share|improve this question




























    0















    I know how to iterate through the attributes of an object. But that excludes attributes realized through getters/setters or @property decorators.



    How can I iterate through those?



    class MyClass:

    def __init__(self):
    self.foo = "bar"

    @property
    def myprop(self):
    return "hello"


    my_instance = MyClass()

    for i in my_instance.__dict__:
    print("object has attribute %s" % i)


    This little script prints:



    object has attribute foo


    What I want though is a script that prints:



    object has attribute foo
    object has attribute myprop









    share|improve this question
























      0












      0








      0








      I know how to iterate through the attributes of an object. But that excludes attributes realized through getters/setters or @property decorators.



      How can I iterate through those?



      class MyClass:

      def __init__(self):
      self.foo = "bar"

      @property
      def myprop(self):
      return "hello"


      my_instance = MyClass()

      for i in my_instance.__dict__:
      print("object has attribute %s" % i)


      This little script prints:



      object has attribute foo


      What I want though is a script that prints:



      object has attribute foo
      object has attribute myprop









      share|improve this question














      I know how to iterate through the attributes of an object. But that excludes attributes realized through getters/setters or @property decorators.



      How can I iterate through those?



      class MyClass:

      def __init__(self):
      self.foo = "bar"

      @property
      def myprop(self):
      return "hello"


      my_instance = MyClass()

      for i in my_instance.__dict__:
      print("object has attribute %s" % i)


      This little script prints:



      object has attribute foo


      What I want though is a script that prints:



      object has attribute foo
      object has attribute myprop






      python python-3.x loops getter






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 12:20









      Flocko MotionFlocko Motion

      4310 bronze badges




      4310 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          0














          You can use dir() to get all the attributes, though that will include methods inherited from base classes, including all the dunder methods from object:



          class MyClass:

          def __init__(self):
          self.foo = "bar"

          @property
          def myprop(self):
          return "hello"


          my_instance = MyClass()

          for i in dir(my_instance):
          print("object has attribute %s" % i)


          prints:



          object has attribute __class__
          object has attribute __delattr__
          object has attribute __dict__
          object has attribute __dir__
          object has attribute __doc__
          object has attribute __eq__
          object has attribute __format__
          object has attribute __ge__
          object has attribute __getattribute__
          object has attribute __gt__
          object has attribute __hash__
          object has attribute __init__
          object has attribute __init_subclass__
          object has attribute __le__
          object has attribute __lt__
          object has attribute __module__
          object has attribute __ne__
          object has attribute __new__
          object has attribute __reduce__
          object has attribute __reduce_ex__
          object has attribute __repr__
          object has attribute __setattr__
          object has attribute __sizeof__
          object has attribute __str__
          object has attribute __subclasshook__
          object has attribute __weakref__
          object has attribute foo
          object has attribute myprop


          You can exclude some with string operations:



          for i in dir(my_instance):
          if i.startswith("__"):
          continue
          print("object has attribute %s" % i)


          prints:



          object has attribute foo
          object has attribute myprop





          share|improve this answer






























            0














            You can look for the property instances in the object class:



            def get_properties(obj):
            cls = type(obj)
            props =
            for k in dir(cls):
            attr = getattr(cls, k)
            # Check that it is a property with a getter
            if isinstance(attr, property) and attr.fget:
            val = attr.fget(obj)
            props[k] = attr.fget(obj)
            return props

            class A(object):
            def __init__(self, p):
            self._p = p
            @property
            def p(self):
            return self._p
            p2 = property(fget=lambda self: 2 * self._p)

            a = A(1)
            a_props = get_properties(a)
            print(a_props)
            # 'p': 1, 'p2': 2





            share|improve this answer























            • Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

              – Flocko Motion
              Mar 26 at 12:44











            • @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

              – jdehesa
              Mar 26 at 12:52













            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%2f55357018%2fhow-to-iterate-through-attributes-of-an-object-defined-by-getters-or-property%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









            0














            You can use dir() to get all the attributes, though that will include methods inherited from base classes, including all the dunder methods from object:



            class MyClass:

            def __init__(self):
            self.foo = "bar"

            @property
            def myprop(self):
            return "hello"


            my_instance = MyClass()

            for i in dir(my_instance):
            print("object has attribute %s" % i)


            prints:



            object has attribute __class__
            object has attribute __delattr__
            object has attribute __dict__
            object has attribute __dir__
            object has attribute __doc__
            object has attribute __eq__
            object has attribute __format__
            object has attribute __ge__
            object has attribute __getattribute__
            object has attribute __gt__
            object has attribute __hash__
            object has attribute __init__
            object has attribute __init_subclass__
            object has attribute __le__
            object has attribute __lt__
            object has attribute __module__
            object has attribute __ne__
            object has attribute __new__
            object has attribute __reduce__
            object has attribute __reduce_ex__
            object has attribute __repr__
            object has attribute __setattr__
            object has attribute __sizeof__
            object has attribute __str__
            object has attribute __subclasshook__
            object has attribute __weakref__
            object has attribute foo
            object has attribute myprop


            You can exclude some with string operations:



            for i in dir(my_instance):
            if i.startswith("__"):
            continue
            print("object has attribute %s" % i)


            prints:



            object has attribute foo
            object has attribute myprop





            share|improve this answer



























              0














              You can use dir() to get all the attributes, though that will include methods inherited from base classes, including all the dunder methods from object:



              class MyClass:

              def __init__(self):
              self.foo = "bar"

              @property
              def myprop(self):
              return "hello"


              my_instance = MyClass()

              for i in dir(my_instance):
              print("object has attribute %s" % i)


              prints:



              object has attribute __class__
              object has attribute __delattr__
              object has attribute __dict__
              object has attribute __dir__
              object has attribute __doc__
              object has attribute __eq__
              object has attribute __format__
              object has attribute __ge__
              object has attribute __getattribute__
              object has attribute __gt__
              object has attribute __hash__
              object has attribute __init__
              object has attribute __init_subclass__
              object has attribute __le__
              object has attribute __lt__
              object has attribute __module__
              object has attribute __ne__
              object has attribute __new__
              object has attribute __reduce__
              object has attribute __reduce_ex__
              object has attribute __repr__
              object has attribute __setattr__
              object has attribute __sizeof__
              object has attribute __str__
              object has attribute __subclasshook__
              object has attribute __weakref__
              object has attribute foo
              object has attribute myprop


              You can exclude some with string operations:



              for i in dir(my_instance):
              if i.startswith("__"):
              continue
              print("object has attribute %s" % i)


              prints:



              object has attribute foo
              object has attribute myprop





              share|improve this answer

























                0












                0








                0







                You can use dir() to get all the attributes, though that will include methods inherited from base classes, including all the dunder methods from object:



                class MyClass:

                def __init__(self):
                self.foo = "bar"

                @property
                def myprop(self):
                return "hello"


                my_instance = MyClass()

                for i in dir(my_instance):
                print("object has attribute %s" % i)


                prints:



                object has attribute __class__
                object has attribute __delattr__
                object has attribute __dict__
                object has attribute __dir__
                object has attribute __doc__
                object has attribute __eq__
                object has attribute __format__
                object has attribute __ge__
                object has attribute __getattribute__
                object has attribute __gt__
                object has attribute __hash__
                object has attribute __init__
                object has attribute __init_subclass__
                object has attribute __le__
                object has attribute __lt__
                object has attribute __module__
                object has attribute __ne__
                object has attribute __new__
                object has attribute __reduce__
                object has attribute __reduce_ex__
                object has attribute __repr__
                object has attribute __setattr__
                object has attribute __sizeof__
                object has attribute __str__
                object has attribute __subclasshook__
                object has attribute __weakref__
                object has attribute foo
                object has attribute myprop


                You can exclude some with string operations:



                for i in dir(my_instance):
                if i.startswith("__"):
                continue
                print("object has attribute %s" % i)


                prints:



                object has attribute foo
                object has attribute myprop





                share|improve this answer













                You can use dir() to get all the attributes, though that will include methods inherited from base classes, including all the dunder methods from object:



                class MyClass:

                def __init__(self):
                self.foo = "bar"

                @property
                def myprop(self):
                return "hello"


                my_instance = MyClass()

                for i in dir(my_instance):
                print("object has attribute %s" % i)


                prints:



                object has attribute __class__
                object has attribute __delattr__
                object has attribute __dict__
                object has attribute __dir__
                object has attribute __doc__
                object has attribute __eq__
                object has attribute __format__
                object has attribute __ge__
                object has attribute __getattribute__
                object has attribute __gt__
                object has attribute __hash__
                object has attribute __init__
                object has attribute __init_subclass__
                object has attribute __le__
                object has attribute __lt__
                object has attribute __module__
                object has attribute __ne__
                object has attribute __new__
                object has attribute __reduce__
                object has attribute __reduce_ex__
                object has attribute __repr__
                object has attribute __setattr__
                object has attribute __sizeof__
                object has attribute __str__
                object has attribute __subclasshook__
                object has attribute __weakref__
                object has attribute foo
                object has attribute myprop


                You can exclude some with string operations:



                for i in dir(my_instance):
                if i.startswith("__"):
                continue
                print("object has attribute %s" % i)


                prints:



                object has attribute foo
                object has attribute myprop






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 26 at 12:27









                Ned BatchelderNed Batchelder

                271k54 gold badges459 silver badges579 bronze badges




                271k54 gold badges459 silver badges579 bronze badges























                    0














                    You can look for the property instances in the object class:



                    def get_properties(obj):
                    cls = type(obj)
                    props =
                    for k in dir(cls):
                    attr = getattr(cls, k)
                    # Check that it is a property with a getter
                    if isinstance(attr, property) and attr.fget:
                    val = attr.fget(obj)
                    props[k] = attr.fget(obj)
                    return props

                    class A(object):
                    def __init__(self, p):
                    self._p = p
                    @property
                    def p(self):
                    return self._p
                    p2 = property(fget=lambda self: 2 * self._p)

                    a = A(1)
                    a_props = get_properties(a)
                    print(a_props)
                    # 'p': 1, 'p2': 2





                    share|improve this answer























                    • Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

                      – Flocko Motion
                      Mar 26 at 12:44











                    • @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

                      – jdehesa
                      Mar 26 at 12:52















                    0














                    You can look for the property instances in the object class:



                    def get_properties(obj):
                    cls = type(obj)
                    props =
                    for k in dir(cls):
                    attr = getattr(cls, k)
                    # Check that it is a property with a getter
                    if isinstance(attr, property) and attr.fget:
                    val = attr.fget(obj)
                    props[k] = attr.fget(obj)
                    return props

                    class A(object):
                    def __init__(self, p):
                    self._p = p
                    @property
                    def p(self):
                    return self._p
                    p2 = property(fget=lambda self: 2 * self._p)

                    a = A(1)
                    a_props = get_properties(a)
                    print(a_props)
                    # 'p': 1, 'p2': 2





                    share|improve this answer























                    • Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

                      – Flocko Motion
                      Mar 26 at 12:44











                    • @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

                      – jdehesa
                      Mar 26 at 12:52













                    0












                    0








                    0







                    You can look for the property instances in the object class:



                    def get_properties(obj):
                    cls = type(obj)
                    props =
                    for k in dir(cls):
                    attr = getattr(cls, k)
                    # Check that it is a property with a getter
                    if isinstance(attr, property) and attr.fget:
                    val = attr.fget(obj)
                    props[k] = attr.fget(obj)
                    return props

                    class A(object):
                    def __init__(self, p):
                    self._p = p
                    @property
                    def p(self):
                    return self._p
                    p2 = property(fget=lambda self: 2 * self._p)

                    a = A(1)
                    a_props = get_properties(a)
                    print(a_props)
                    # 'p': 1, 'p2': 2





                    share|improve this answer













                    You can look for the property instances in the object class:



                    def get_properties(obj):
                    cls = type(obj)
                    props =
                    for k in dir(cls):
                    attr = getattr(cls, k)
                    # Check that it is a property with a getter
                    if isinstance(attr, property) and attr.fget:
                    val = attr.fget(obj)
                    props[k] = attr.fget(obj)
                    return props

                    class A(object):
                    def __init__(self, p):
                    self._p = p
                    @property
                    def p(self):
                    return self._p
                    p2 = property(fget=lambda self: 2 * self._p)

                    a = A(1)
                    a_props = get_properties(a)
                    print(a_props)
                    # 'p': 1, 'p2': 2






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 26 at 12:33









                    jdehesajdehesa

                    32.8k4 gold badges39 silver badges61 bronze badges




                    32.8k4 gold badges39 silver badges61 bronze badges












                    • Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

                      – Flocko Motion
                      Mar 26 at 12:44











                    • @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

                      – jdehesa
                      Mar 26 at 12:52

















                    • Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

                      – Flocko Motion
                      Mar 26 at 12:44











                    • @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

                      – jdehesa
                      Mar 26 at 12:52
















                    Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

                    – Flocko Motion
                    Mar 26 at 12:44





                    Seems to be more complicated.. What would be the advantage of your solution over Ned Batchelders way?

                    – Flocko Motion
                    Mar 26 at 12:44













                    @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

                    – jdehesa
                    Mar 26 at 12:52





                    @FlockoMotion Well I don't exactly claim there is an "advantage", more just an "alternative way to do it". May be better or worse depending on what you want. If you want to specifically collect the properties in an object, (attributes declared with property), then this is specifically that. If you just want to know every <something> for which you can do obj.<something> then that's Ned's answer (that includes for example method names as well).

                    – jdehesa
                    Mar 26 at 12:52

















                    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%2f55357018%2fhow-to-iterate-through-attributes-of-an-object-defined-by-getters-or-property%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현