[英]Function templates in python
我想知道如何在python中使用与模板<typename T>类似的代码,因为它在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;
}
我将如何像在C ++中提到的那样在python中使用变量类型名对对象进行类型转换?
通过使用Python的闭包,通过应用模板为特定类型创建函数,DeepSpace的答案可以被修饰为使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'
只需将类型传递给函数即可。
例如,请参见此(无用)函数:
def converter(x, required_type):
return required_type(x)
converter('1', int)
converter('1', float)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.