重写 python 函数而不使用检查模块
在不使用检查模块的情况下,我将如何编写这个内省函数。
import inspect
def trace(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
setattr(cls,name,log(m))
return cls
以上来自 这个问题/回答
编辑/澄清: 是否可以在不进行任何导入的情况下执行此操作?
请注意,这不是一个真正的用例,而是我出于好奇而纯粹而简单的案例。
How would I write this introspective function without using the inspect module.
import inspect
def trace(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
setattr(cls,name,log(m))
return cls
The above is from this SO question/answer
Edit/Clarification:
Is it possible to do this without any imports also?
Note this is not a real use case rather a pure and simple case of curiosity on my part.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
inspect.ismmethod
的作用是 简单< /a>:和
types.MethodType
是 定义为:What
inspect.ismethod
does is simply:and
types.MethodType
is defined as:如果不使用检查,我会这样做:
编辑:
你的约束有点奇怪,但让我们看看:
我们可以用<替换
if isinstance(attr, types.MethodType)
code>if callable(attr) 这将只给我们类的可调用属性,其中还包括静态方法和类方法...我们也可以按照其他答案建议使用
if hasattr(attr, 'im_func')
这将排除静态方法。如果我们也想排除类方法(仅获取实例方法),我认为我现在知道的唯一解决方案(不导入其他模块)是通过更改装饰器来检查第一个参数是类还是实例,这可以给您提示将要修饰的方法是类方法还是实例方法。
希望它有帮助:)
Without using inspect i will do it like this:
EDIT:
Your constrain are a bit weird but let see :
We can replace
if isinstance(attr, types.MethodType)
byif callable(attr)
this will give us only callable attribute of the class which include also static methods and class methods ...We can also do as the other answer suggest use
if hasattr(attr, 'im_func')
this will exclude the static methods.If we want to exclude class method too (only get instance method), i think the only solution i'm aware off now (without importing an other module) is by changing the decorator to check if the first argument is a class or an instance, this can give you a hint if the method that will be decorated is a class or a instance method.
Hope it help :)
像这样的东西:
来自数据模型 向下滚动一点到达“用户定义的方法”。
自 2.6 起,im_func 和 im_self 也分别可用作
__func__
和__self__
。我有点倾向于这里而不是自己使用检查模块。
something like this:
from the python docs on the data model scroll down a bit to get to "user defined methods".
im_func and im_self as of 2.6 are also availabale as
__func__
and__self__
respectively.I sort of tend to gravitate here than use the inspect module myself.