Python Forum
Listing Attributes of Objects & Classes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Listing Attributes of Objects & Classes
#1
Hello all

I have started to create classes and objects in python, progress is slow but i am getting there.

I wanted to ask the community whether it was possible to output all the attributes of a class/object.

I have created the following class:-

import inspect

class Helloclass:
    
    def __init__(self):
        self.A = ""
        self.B = ""
        self.C = ""
        self.D = ""

london = Helloclass()
london.A = "Apples"
london.D = 120

print(inspect.getmembers(london))
I have created an object called london from Helloclass (so london is an instance of Helloclass).

There are 4 x properties that i coded into the class these are A, B, C, D.

I have assigned the string Apples to the A attribute of the london object.

I have assigned the value 120 to the A attribute of the london object.

I wanted to print out all of the available properties of the london object or the Helloclass Class.

I have used the module inspect, however this gives me a horrible out and looks like:-

[('A', 'Apples'), ('B', ''), ('C', ''), ('D', 120), ('__class__', <class '__main__.Helloclass'>), ('__delattr__', <method-wrapper '__delattr__' of Helloclass object at 0x000001E6B704CD00>), ('__dict__', {'A': 'Apples', 'B': '', 'C': '', 'D': 120}), ('__dir__', <built-in method __dir__ of Helloclass object at 0x000001E6B704CD00>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of Helloclass object at 0x000001E6B704CD00>), ('__format__', <built-in method __format__ of Helloclass object at 0x000001E6B704CD00>), ('__ge__', <method-wrapper '__ge__' of Helloclass object at 0x000001E6B704CD00>), ('__getattribute__', <method-wrapper '__getattribute__' of Helloclass object at 0x000001E6B704CD00>), ('__gt__', <method-wrapper '__gt__' of Helloclass object at 0x000001E6B704CD00>), ('__hash__', <method-wrapper '__hash__' of Helloclass object at 0x000001E6B704CD00>), ('__init__', <bound method Helloclass.__init__ of <__main__.Helloclass object at 0x000001E6B704CD00>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x000001E6B57CF350>), ('__le__', <method-wrapper '__le__' of Helloclass object at 0x000001E6B704CD00>), ('__lt__', <method-wrapper '__lt__' of Helloclass object at 0x000001E6B704CD00>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of Helloclass object at 0x000001E6B704CD00>), ('__new__', <built-in method __new__ of type object at 0x00007FFF9F7DCB50>), ('__reduce__', <built-in method __reduce__ of Helloclass object at 0x000001E6B704CD00>), ('__reduce_ex__', <built-in method __reduce_ex__ of Helloclass object at 0x000001E6B704CD00>), ('__repr__', <method-wrapper '__repr__' of Helloclass object at 0x000001E6B704CD00>), ('__setattr__', <method-wrapper '__setattr__' of Helloclass object at 0x000001E6B704CD00>), ('__sizeof__', <built-in method __sizeof__ of Helloclass object at 0x000001E6B704CD00>), ('__str__', <method-wrapper '__str__' of Helloclass object at 0x000001E6B704CD00>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x000001E6B57CF350>), ('__weakref__', None)]
Although this gives me what i want, there is so much extra stuff which i do not need or want to see.

I just want the output to be something like:-
london Object of Class Helloclass
london.A = "Apples"
london.B = ""
london.C = ""
london.D = 120

Is there anyway of getting a cleaner out?

Thank you.
Reply
#2
You could define your own function, such as
def report(obj, name=None):
    name = name or 'obj'
    L = ['{} Object of Class {}'.format(name, type(obj).__name__)]
    for k, v in vars(obj).items():
        L.append('{}.{} = {}'.format(name, k, repr(v)))
    return '\n'.join(L)

print(report(london, 'london'))
Reply
#3
Use vars().

In [1]: class Helloclass:
   ...:
   ...:     def __init__(self):
   ...:         self.A = ""
   ...:         self.B = ""
   ...:         self.C = ""
   ...:         self.D = ""
   ...:
   ...: london = Helloclass()
   ...: london.A = "Apples"
   ...: london.D = 120
   ...:
   ...: print(vars(london))
   ...: print(london.__dict__)
   ...:
   ...:
{'A': 'Apples', 'B': '', 'C': '', 'D': 120}
{'A': 'Apples', 'B': '', 'C': '', 'D': 120}
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
(Aug-27-2020, 06:30 AM)Gribouillis Wrote: You could define your own function, such as
def report(obj, name=None):
    name = name or 'obj'
    L = ['{} Object of Class {}'.format(name, type(obj).__name__)]
    for k, v in vars(obj).items():
        L.append('{}.{} = {}'.format(name, k, repr(v)))
    return '\n'.join(L)

print(report(london, 'london'))

Thanks
Reply
#5
Out of interest, why? You know what the attributes are, so why not just print them out? If you were implementing __str__, you'd be providing your own string representation of the object.

Also, your class doesn't seem to be a well defined thing. Perhaps you're not really understanding what classes are for?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [solved] Classes, assign an attributes to a class not to instances.. SpongeB0B 4 934 May-20-2023, 04:08 PM
Last Post: SpongeB0B
  Listing directories (as a text file) kiwi99 1 838 Feb-17-2023, 12:58 PM
Last Post: Larz60+
  Read directory listing of files and parse out the highest number? cubangt 5 2,349 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  Listing All Methods Of Associated With A Class JoeDainton123 3 2,345 May-10-2021, 01:46 AM
Last Post: deanhystad
  Listing files with glob. MathCommander 9 4,955 Oct-26-2020, 02:04 AM
Last Post: MathCommander
  Listing data from a list ebolisa 1 1,746 Sep-29-2020, 02:24 PM
Last Post: DeaD_EyE
  Getting attributes from a list containing classes midarq 2 2,161 Dec-03-2019, 12:42 AM
Last Post: midarq
  Listing groups tharpa 2 2,575 Nov-26-2019, 07:25 AM
Last Post: DeaD_EyE
  AWS lambda script help - Listing untagged volumes jutler 0 2,251 Feb-13-2019, 02:36 PM
Last Post: jutler
  Classes and Objects - question AI_ML_Neophyte 3 2,915 Dec-11-2018, 01:52 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020