Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use str.format() to access object attributes

People also ask

What is str format in Python?

Learn about string formatting in Python. String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. As a data scientist, you would use it for inserting a title in a graph, show a message or an error, or pass a statement to a function.

How do you access data from an object in Python?

Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

How do you check a string format in Python?

Use time. strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError . Show activity on this post.

What is formatted printing in Python?

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. The str.format()method of strings help a user to get a fancier Output. User can do all the string handling by using string slicing and concatenation operations to create any layout that user wants.


You can use the .attribute_name notation inside the format fields themselves:

print 'My object has strings a={0.a}, b={0.b}, c={0.c}'.format(obj)

Below is a demonstration:

>>> class Test(object):
...     def __init__(self, a, b, c):
...         self.a = a
...         self.b = b
...         self.c = c
...
>>> obj = Test(1, 2, 3)
>>> 'My object has strings a={0.a}, b={0.b}, c={0.c}'.format(obj)
'My object has strings a=1, b=2, c=3'
>>>

Note however that you do need to number the format fields when doing this. Also, as you can see, the str.format function has its format fields denoted by curly braces {...}, not the % sign.

For more information, here is a reference on the Format String Syntax in Python.


I think it's preferable to use vars() to access an object's attributes as a dict rather than usng __dict__.

So you could do this:

"My object has strings a={a}, b={b}, c={c}".format(**vars(obj))

For more background on why vars() is preferable to __dict__, see the answer to the question Use dict or vars()?.


As @igniteflow wrote in a buried comment:

'My object has strings a={a}, b={b}, c={c}'.format(**obj.__dict__)

With my limited python understanding: .__dict__ is a dict with all the instances attributes and the ** operator basically unpacks them and adds them as key=value args to the method


For the sake of completeness, building on @igniteflow and @Christian, you could use the % string format operator and write:

'My object has strings a=%(a)s, b=%(b)s, c=%(c)s' % obj.__dict__