Python class method
-
21-12-2019 - |
Question
I have a class instance of type <class 'openstack_dashboard.api.nova.Server'>
:
>>>print instance
>>><Server: {'id': u'9fa3b2e9-a76b-44ae-be75-968d4010eb27',
'links': [{u'href': u'http://10.0.3.129:8774/v2/344f7fa036fc45008130cdf1cffac019/servers/9fa3b2e9-a76b-44ae-be75-968d4010eb27', u'rel': u'self'},
{u'href': u'http://10.0.3.129:8774/344f7fa036fc45008130cdf1cffac019/servers/9fa3b2e9-a76b-44ae-be75-968d4010eb27', u'rel': u'bookmark'}]}>
>>> print dir(instance)
>>> ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattr__', '__getattribute__', '__hash__', '__init__',
'__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', '_apiresource', '_attrs', 'image_name',
'internal_name', 'request']
I want to get the 'id'
('9fa3b2e9-a76b-44ae-be75-968d4010eb27'
).
What should I do ? Thank you !
Solution
According to what I can see in the source, Server
inherits from the common APIResourceWrapper, which in turn implements __gatattr__
so that id
, while it's not exactly an object's own attribute, will be taken from the internal container self._apiresource
.
So, instance.id
will work and will effectively return instance._apiresource.id
.
OTHER TIPS
Class openstack_dashboard.api.nova.Server
inherits from openstack_dashboard.api.base.APIResourceWrapper
and this class has defined __getattr__()
method which uses self._attrs
, so I think it should be possible to read id
in this way:
print(instance.id)
This might work now for you, but it's implementation-dependent:
import re
printed = instance.__str__() #might also be __repr__()
m = re.search("'id'\s*:\s*u'([\w+\-]+)'", printed)
m.groups(0)[0] #returns 9fa3b2e9-a76b-44ae-be75-968d4010eb27