isinstance 函数似乎施加魔法,可以自动判断? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
James369

isinstance 函数似乎施加魔法,可以自动判断?

  •  
  •   James369 May 14, 2021 1949 views
    This topic created in 1808 days ago, the information mentioned may be changed or developed.

    我在构造一个自定义迭代器 Test 类的时候发现一个奇特的现象,Test 类并没有继承自 Iterable,只是实现了__iter__和__next__函数。

    然而创建的对象却可以判定是 Iterable 类型

    class TestIterator(): def __init__(self, n): ... def __iter__(self): return self def __next__(self): ... t1 = Test() isinstance(t1, Iterable) #返回 True !!! 

    然后我又创建了一组普通的类测试,发现又不行了:

    class A: def do1(self): print('A do1') class B(A): def do2(self): print('B do2') class X: def do1(self): print('X do1') a1 = A() b1 = B() x1 = X() isinstance(b1, A) #True isinstance(x1, A) #False ??? 
    4 replies    2021-05-14 16:53:22 +08:00
    fengjianxinghun
        1
    fengjianxinghun  
       May 14, 2021   2
    假如你看起来像鸭子,叫起来像鸭子,走起路来像鸭子,那你就是鸭子。


    https://docs.python.org/3/library/stdtypes.html#typeiter
    knightdf
        2
    knightdf  
       May 14, 2021   1
    建议你看看 collections.abc.Iterable 的文档
    geelaw
        3
    geelaw  
       May 14, 2021   1
    答案是因为 Iterable 是抽象基类 (abstract base class),但 A 不是。isinstance 对于抽象基类 (ABC) 有特殊的规则。

    https://docs.python.org/3/library/functions.html#isinstance

    当 object 是 classinfo 或它(直接、间接、虚拟)子类的实例时,返回 True 。

    点击“虚拟”,可以看到

    https://docs.python.org/3/glossary.html#term-abstract-base-class

    ABC 引入虚拟子类虽然不继承,但 isinstance()、issubclass() 仍然识别为子类。
    abersheeran
        4
    abersheeran  
       May 14, 2021   1
    https://docs.python.org/3/reference/datamodel.html?highlight=instancecheck#class.__instancecheck__ 为你的 A 实现一个 __instancecheck__ 用以检查 do1 是否存在就行。

    如果你觉得手工穷举检查麻烦,可以使用 https://docs.python.org/zh-cn/3/library/typing.html#typing.runtime_checkable
    About     Help     Advertise     Blog     API     FAQ     Solana     1175 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 30ms UTC 23:44 PVG 07:44 LAX 16:44 JFK 19:44
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86