In this simple case you can use vars():
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
Answer from Jochen Ritzel on Stack OverflowIn this simple case you can use vars():
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
Another way is to call the dir() function (see https://docs.python.org/2/library/functions.html#dir).
a = Animal()
dir(a)
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'age', 'color', 'kids', 'legs', 'name', 'smell']
Note, that dir() tries to reach any attribute that is possible to reach.
Then you can access the attributes e.g. by filtering with double underscores:
attributes = [attr for attr in dir(a)
if not attr.startswith('__')]
This is just an example of what is possible to do with dir(), please check the other answers for proper way of doing this.
python - Is there a built-in function to print all the current properties and values of an object? - Stack Overflow
python - List attributes of an object - Stack Overflow
Print Object Attributes in Python - Ask a Question - TestMu AI Community
print class attributes from a list?
Videos
If I have the below code, how can I write a print statement to show the values of self.1, self.2, and self.3?
class Name:
def __init__(self):
self.1 = "a"
self.2 = "b"
self.3 = "c"You want vars() mixed with pprint():
from pprint import pprint
pprint(vars(your_object))
You are really mixing together two different things.
Use dir(), vars() or the inspect module to get what you are interested in (I use __builtins__ as an example; you can use any object instead).
>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
Print that dictionary however fancy you like:
>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...
or
>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
...
'_': [ 'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
Pretty printing is also available in the interactive debugger as a command:
(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
'BaseException': <type 'exceptions.BaseException'>,
'BufferError': <type 'exceptions.BufferError'>,
...
'zip': <built-in function zip>},
'__file__': 'pass.py',
'__name__': '__main__'}
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__
Then you can test what type is with type() or if is a method with callable().
I've got a class Car, I have instances of car in the main body of the code, I've added the car instances to a list and now want to print specific elements of that list, but it just print's "<__main__.Car object at 0x00000297B91FF040>" or "None" I need it to print
("AT11CAR", "Audi", "R8", "Black", "1000", "500", "Dundee", "3")
without the brackets etc. If someone chooses Audi, it print's the first two cars from the lists' information (the line above). I have multiple car makes in this list so I don't really want to do for car in car print(car) or know away around it. Anything will help, thanks.
Here's a snippet: https://pastebin.com/QCgkY69E
any help is appreciated thank you.