简体   繁体   中英

Printing the class object in python

I am working in modifications of codes in Openstack Designate.

During the same I need to print some data.

When I checked for type of the same, it returned the details as follows:

<class 'designate.openstack.common.rpc.amqp.RpcContext'>

When I tried to log the same (for printing), It is returning the details as follows:

<designate.openstack.common.rpc.amqp.RpcContext object at 0x7f7552b08250>

I know that it contains the tenant_id, So when I am trying to print the same it is working fine.

LOG.info(context.tenant_id)

Now I need to know or see what is inside:

<designate.openstack.common.rpc.amqp.RpcContext object at 0x7f7552b08250>

That is inside 'context'.

What I need is simply printing the details which resides inside 'context'

Read abount __repr__ and __str__

__repr__ is a "official" string representation of the object

__str__ is a "informal" string representation of the object

You can overwrite both functions in a class.

For more info read Difference between __str__ and __repr__ in Python

In your case You can write:

def __str__(self):
    return '%d' % self.tenant_id

anything related to oslo-incubator should be changed in openstack/oslo-incubator then synced to designate projects

however, most of the code has been graduated from oslo-incubator, the rpc module in oslo-incubator seems no longer exist, so it seems you are developing based on a (old) stable branch

so I guess you just need to find out what is in it.

as you already done for tenant_id, just add a log to print:

LOG.info('attr=%s, content=%s', dir(context), context.__dict__) 

would be fine

Maybe you can use this little trick:

def info_obj(a):
    for x in dir(a):
        if not x.startswith('_'):
           print(x, ,'=', a.__getattribute__(x))

dir(a) will return the names of all the attributes of the object, and __getattribute__ will get its value. I'm skipping the ones that start with _ because these are usually not to be seen by users of the objects.

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