简体   繁体   中英

How is this string being formatted in python

I am going through a tutorial for a python library. Found this example code :

>>> device = monitor.poll(timeout=3)
>>> if device:
...     print('{0.action}: {0}'.format(device))
...

I know the meaning of {0} and in this .format() template. What does {0.action} mean and how does it get processed?

An instructive example:

>>> class Device:
    def __init__(self):
        self.action = "bar"
    def __str__(self):
        return "foo"


>>> device = Device()
>>> print('{0.action}: {0}'.format(device))
bar: foo

The "dot notation" instance.attribute can be used to access attributes in str.format just as it can elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM