【问题标题】:Function templates in pythonpython中的函数模板
【发布时间】:2016-12-15 01:52:43
【问题描述】:

我想知道如何在 python 中使用与 template 类似的代码,因为它在 C++ 代码示例中使用:

template <typename T>
unsigned int counting_bit(unsigned int v){
   v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
   v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
   v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
   return v;
}

如何在 python 中以与 C++ 中提到的相同的方式对具有变量 typename 的对象进行类型转换?

【问题讨论】:

  • 到目前为止你的python代码是什么?
  • 即使使用 C++,是否需要 template 来计算位数?有一个n &amp; (n - 1) 使用循环计数位的技巧。
  • @VaibhavBajaj 我还没有编写 python 代码,因为我仍在试图弄清楚如何对对象进行类型转换。
  • 你要在 python 中传递什么T? python默认只有一种整数类型,你要不要用ctypes
  • @Holt 我会通过 ctypes,我也觉得 DeepSpace 的回答很有帮助。

标签: python c++ templates function-templates


【解决方案1】:

DeepSpace 的答案可以通过使用 Python 的闭包执行以下操作(有时称为 factory functionfunction factory 来修饰以使事情更像 C++ -通过应用模板为特定类型创建函数。它还显示了在 Python 中获取和使用另一个变量的类型是多么容易。

def converter_template(typename):
    def converter(v):
        t = typename(v)  # convert to numeric for multiply
        return type(v)(t * 2)  # value returned converted back to original type

    return converter

int_converter = converter_template(int)
float_converter = converter_template(float)

print('{!r}'.format(int_converter('21')))    # '42'
print('{!r}'.format(float_converter('21')))  # '42.0'

【讨论】:

    【解决方案2】:

    只需将类型传递给函数。

    比如看这个(没用的)函数:

    def converter(x, required_type):
        return required_type(x)
    
    converter('1', int)
    converter('1', float)
    

    【讨论】:

    • 这是一个很好的解决方案,并且很容易帮助到我。我想知道天气是否可以传递 ctypes 数据类型并返回例如 c_int().value?
    • 你可以传递和返回任何python对象。
    猜你喜欢
    • 2022-10-08
    • 2012-01-28
    • 2018-02-06
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多