Reputation: 22113
How to retrieve the detailed statements of an object's method? Supposed an class:
class Car:
def __init__(self,make, model,year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
return self.make + ' ' + self.model + ' ' + str(self.year)
Copied it to console and create an instance.
my_new_car = Car('Mars_Rocket','MR5',2017)
Retrieve info:
In [52]: vars(my_new_car)
Out[52]: {'make': 'Mars_Rocket', 'model': 'MR5', 'year': 2017}
Nevertheless,what I want is:
{'make': 'Mars_Rocket', 'model': 'MR5', 'year': 2017 \
'get_descriptive_name':'self.make + ' ' + self.model + ' ' + str(self.year)'}
One more step, I try dir()
:
In [53]: attrs = [ i for i in dir(my_new_car) if not i.startswith('__')]
In [54]: attrs
Out[54]: ['get_descriptive_name', 'make', 'model', 'year']
In [57]: {attr:getattr(my_new_car, attr) for attr in attrs }
Out[57]:
{'get_descriptive_name': <bound method Car.get_descriptive_name of <__main__.Car object at 0x10517deb8>>,
'make': 'Mars_Rocket',
'model': 'MR5',
'year': 2017}
Despite of acquiring the method, a detailed statement is still unloaded.
How to obtain the statement block of an object's method in interactive mode of console?
Upvotes: 1
Views: 46
Reputation: 160607
Make a little helper that uses inspect.getsourcelines
to grab the method contents:
from inspect import getsourcelines
from types import MethodType
def mydir(obj):
names = [name for name in dir(obj) if not name.startswith('__')]
for name in names:
val = getattr(obj, name)
if not isinstance(val, MethodType):
yield (name, val)
else:
val = "\n".join(map(str.strip, getsourcelines(val)[0][1:])
yield (name, val)
this assumes an instance is passed and then goes through the names in the object and if they aren't of Method
type it just returns their name and value. If they are it uses getsourcelines
, removes the first line (function def) and strips indentation (probably not a good idea).
It yields tuples which you can feed into dict
:
dict(mydir(my_new_car))
Out[33]:
{'get_descriptive_name': "return self.make + ' ' + self.model + ' ' + str(self.year)",
'make': 'Mars_Rocket',
'model': 'MR5',
'year': '2017'}
It grabs all contents in the method, return
is also included (it's a statement).
Upvotes: 1