introspection - How would you determine where each property and method of a Python class is defined? -
Looking at an example of some class in Python, it will be able to determine which line defined < / Em> each method and property (for example to apply). For example, a module has been given
class A (object): z = 1 q = 2 def y (self): def def x (self): pass class B (A) ): Q = 4 def x (self): pass def w (self): pass
define a function (class_, attribute) where the filename, class, source code that defines Or subclass is attribute
. This is a definition in the class body, and not the latest assignment due to overriar dynamics. This is fine if it gives 'unknown' to some features.
& gt; & Gt; & Gt; A = A ()> & Gt; & Gt; B = B ()> gt; & Gt; & Gt; B.spigot = 'bronze' & gt; & Gt; & Gt; Where (a, 'z') ("ab.py", & lt; square 'a.a' & gt; [line] 2)> gt; & Gt; & Gt; Where (b, 'q') ("ab.py", & lt; square 'a.b' & gt; 8) & gt; & Gt; & Gt; Where (b, 'x') ("ab.py",
I want to use it this time, in which there are hundreds of ways of every object And it should be really useful to organize by class, not only alphabetically.
Of course, in Python you do not always know knowingly, but in general, usually to get a good answer Good-to-body code.
It is more or less impossible without static analysis, and still, it will not always work You can get that line Where the function was defined and by examining the code object of the code, but beyond that, you can not do this. Inspection
module can help with this:
import ab a = ab.A () meth = ax # So, now we have the method Func = meth.im_func # and method by function code = func.func_c Code from ode # and function! Print code.co_firstlineno, code.co_filename # or: Inspect the import inspection print inspection (meth), inspect.getfile (meth)
:
Def some_method (self): ABAA Swim_methu = some_mafation aba. AOM_clas_accountivity = any
or worse: passport
some_cls = ab a some_string_var = 'another_instance_attribute' setattr (some_cls, some_string_var, none) < / Code>
Specifically in the latter case, what do you expect or want to achieve?
Comments
Post a Comment