Python:如何检查...?
我想要一些关于如何检查我收到的参数的正确性的建议。
检查将在 C++ 中完成,因此如果有使用 Boost.Python(最好)或 C API 的良好解决方案,请告诉我。否则,请告诉我该对象应具有哪些属性以确保其满足标准。
那么...
- 如何检查一个对象是否是一个函数?
- 如何检查对象是否是绑定方法?
- 如何检查一个对象是否是一个类对象?
- 如何检查一个类对象是否是另一个类的子对象?
I'd like some advice on how to check for the correctness of the parameters I receive.
The checking is going to be done in C++, so if there's a good solution using Boost.Python (preferably) or the C API, please tell me about that. Otherwise, tell me what attributes the object should have to ensure that it meets the criteria.
So...
- How do you check that an object is a function?
- How do you check that an object is a bound method?
- How do you check that an object is a class object?
- How do you check that a class object is a child of another class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果有疑问,只需弄清楚如何通过调用常用的 Python 内置函数并将其转换为 C/C++ 来获得所需的效果。我只回答Python,对于C,你会查找全局变量,例如“callable”,然后像任何其他Python函数一样调用它。
为什么你会关心它是一个函数而不是任何其他类型的可调用函数?如果您愿意,可以使用内置的
callable(f)
来了解它是否可调用,但当然这不会告诉您调用它时需要传递哪些参数。这里最好的事情通常就是调用它并看看会发生什么。isinstance(f, types.MethodType)
但如果它是内置方法,则没有帮助。由于调用函数或绑定方法的方式没有区别,您可能只想检查它是否可以像上面那样调用。isinstance(someclass, type)
请注意,这将包括内置类型。issubclass(someclass, 基类)
When in doubt just work out how you would get the required effect by calling the usual Python builtins and translate it to C/C++. I'll just answer for Python, for C you would look up the global such as 'callable' and then call it like any other Python function.
Why would you care about it being a function rather than any other sort of callable? If you want you can find out if it is callable by using the builtin
callable(f)
but of course that won't tell you which arguments you need to pass when calling it. The best thing here is usually just to call it and see what happens.isinstance(f, types.MethodType)
but that won't help if it's a method of a builtin. Since there's no difference in how you call a function or a bound method you probably just want to check if it is callable as above.isinstance(someclass, type)
Note that this will include builtin types.issubclass(someclass, baseclass)
我有两个非常规的建议给你:
1)不要检查。 Python 文化是根据需要简单地使用对象,如果不起作用,就会发生异常。提前检查会增加开销,并可能限制人们使用您的代码的方式,因为您的检查比您需要的更严格。
2)不要检查C++。当结合 Python 和 C(或 C++)时,我建议只在 C++ 中做需要在 C++ 中完成的事情。其他一切都应该用 Python 完成。因此,请检查 Python 包装函数中的参数,然后调用未经检查的 C++ 入口点。
I have two unconventional recommendations for you:
1) Don't check. The Python culture is to simply use objects as you need to, and if it doesn't work, then an exception will occur. Checking ahead of time adds overhead, and potentially limits how people can use your code because you're checking more strictly than you need to.
2) Don't check in C++. When combining Python and C (or C++), I recommend only doing things in C++ that need to be done there. Everything else should be done in Python. So check your parameters in a Python wrapper function, and then call an unchecked C++ entry point.