这两个代码片段之间有什么区别?使用type():
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
使用isinstance():
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
Run Code Online (Sandbox Code Playgroud) 我正在练习使用Python 3.5中的类型提示.我的一位同事使用typing.Dict:
import typing
def change_bandwidths(new_bandwidths: typing.Dict,
user_id: int,
user_name: str) -> bool:
print(new_bandwidths, user_id, user_name)
return False
def my_change_bandwidths(new_bandwidths: dict,
user_id: int,
user_name: str) ->bool:
print(new_bandwidths, user_id, user_name)
return True
def main():
my_id, my_name = 23, "Tiras"
simple_dict = {"Hello": "Moon"}
change_bandwidths(simple_dict, my_id, my_name)
new_dict = {"new": "energy source"}
my_change_bandwidths(new_dict, my_id, my_name)
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
它们都工作得很好,似乎没有区别.
我已经阅读了typing模块文档.
之间typing.Dict或dict哪一个,我应该在程序中使用?