你会如何确定每个酒店和方法的蟒蛇类的定义?
-
20-08-2019 - |
题
给出的实例,一些类蟒蛇,这将是有用的,能够确定哪些线的源代码 定义 每种方法和财产(例如实施 1).例如,给定一个模块ab.py
class A(object):
z = 1
q = 2
def y(self): pass
def x(self): pass
class B(A):
q = 4
def x(self): pass
def w(self): pass
定义一个功能往那(class_、属性)返回元组包含该文件名、类和路线的源代码的定义或子类 attribute
.这意味着定义中的类的身体,而不是最新分配由于热切活力。它是好的,如果返回"未知"对于某些属性。
>>> a = A()
>>> b = B()
>>> b.spigot = 'brass'
>>> whither(a, 'z')
("ab.py", <class 'a.A'>, [line] 2)
>>> whither(b, 'q')
("ab.py", <class 'a.B'>, 8)
>>> whither(b, 'x')
("ab.py", <class 'a.B'>, 9)
>>> whither(b, 'spigot')
("Attribute 'spigot' is a data attribute")
我想利用这一点的同时检查Plone,在那里每一个目的有数以百计的方法和这将是真正有用的排序通过他们举办类,而不只是字母顺序排列。
当然,蟒蛇,你总不能合理地知道,但它会漂亮得到很好的答案在公共的情况下大多是静态的代码。
解决方案 2
您正在寻找无证功能inspect.classify_class_attrs(cls)
。它传递的一类,它会返回记录('name', 'kind' e.g. 'method' or 'data', defining class, property)
的列表。如果您需要绝对的一切都在一个特定实例的信息,你必须做额外的工作。
示例:
>>> import inspect
>>> import pprint
>>> import calendar
>>>
>>> hc = calendar.HTMLCalendar()
>>> hc.__class__.pathos = None
>>> calendar.Calendar.phobos = None
>>> pprint.pprint(inspect.classify_class_attrs(hc.__class__))
[...
('__doc__',
'data',
<class 'calendar.HTMLCalendar'>,
'\n This calendar returns complete HTML pages.\n '),
...
('__new__',
'data',
<type 'object'>,
<built-in method __new__ of type object at 0x814fac0>),
...
('cssclasses',
'data',
<class 'calendar.HTMLCalendar'>,
['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']),
('firstweekday',
'property',
<class 'calendar.Calendar'>,
<property object at 0x98b8c34>),
('formatday',
'method',
<class 'calendar.HTMLCalendar'>,
<function formatday at 0x98b7bc4>),
...
('pathos', 'data', <class 'calendar.HTMLCalendar'>, None),
('phobos', 'data', <class 'calendar.Calendar'>, None),
...
]
其他提示
这是更多或更少不可能没有静态分析,即使这样,也不会总是工作。您可以通过检查其代码对象获得其中定义的函数线和哪个文件,但除此之外,有没有什么可以做。该inspect
模块可以帮助这一点。所以:
import ab
a = ab.A()
meth = a.x
# So, now we have the method.
func = meth.im_func
# And the function from the method.
code = func.func_code
# And the code from the function!
print code.co_firstlineno, code.co_filename
# Or:
import inspect
print inspect.getsource(meth), inspect.getfile(meth)
但是,考虑:
def some_method(self):
pass
ab.A.some_method = some_method
ab.A.some_class_attribute = None
或者更糟:
some_cls = ab.A
some_string_var = 'another_instance_attribute'
setattr(some_cls, some_string_var, None)
特别是在后一种情况下,你有什么想要或希望得到?
您正在寻找检查模块,具体inspect.getsourcefile()
和inspect.getsourcelines()
。例如
a.py:
class Hello(object):
def say(self):
print 1
>>> from a import Hello
>>> hi = Hello()
>>> inspect.getsourcefile(hi.say)
a.py
>>> inspect.getsourcelines(A, foo)
([' def say(self):\n print 1\n'], 2)
鉴于Python中的动态特性,这样做了更复杂的情况可以简单地是不可能...
不隶属于 StackOverflow