如何在 python 中执行类似于我在 C# .NET 中使用的以下机制的泛型类型转换:
string typetoConvertTo = "System.String";
string value = (string)Convert.ChangeType( "1", Type.GetType( typetoConvertTo ));
typetoConvertTo = "System.Int32";
int value1 = (int)Convert.ChangeType( "1", Type.GetType(typetoConvertTo));
Run Code Online (Sandbox Code Playgroud)
Python 具有针对单个类型的类型转换,但我需要更通用的方法,例如 .NET 中的上述方法,因为我正在存储类型并且稍后需要执行通用转换。
value = str(100)
value1 = int("100")
Run Code Online (Sandbox Code Playgroud)
类是 Python 中的一流对象。
>>> t = str
>>> t(123)
'123'
>>> d = {'str': str}
>>> d['str'](123)
'123'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1634 次 |
| 最近记录: |