相关疑难解决方法(0)

type()和isinstance()之间有什么区别?

这两个代码片段之间有什么区别?使用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 oop inheritance types

1163
推荐指数
6
解决办法
69万
查看次数

定义typing.Dict和dict之间的区别?

我正在练习使用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.Dictdict哪一个,我应该在程序中使用?

python dictionary type-hinting

58
推荐指数
4
解决办法
2万
查看次数

标签 统计

python ×2

dictionary ×1

inheritance ×1

oop ×1

type-hinting ×1

types ×1