[英]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.