V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
oahebky
V2EX  ›  Python

开个帖子,专门写( Python )bug 代码。仅供娱 mai 乐 lei(参考);应该会不定期更新在评论区

  •  
  •   oahebky · 2020-09-22 22:28:58 +08:00 · 1290 次点击
    这是一个创建于 1283 天前的主题,其中的信息可能已经有所发展或是发生改变。

    rt.


    写 bug 操练 👇

    写 bug 1 -- 概率性抛出异常类无属性异常:

    from random import randint
    
    class Baba:
        def __init__(self):
            self.sex = 'male'
    
        def __getattribute__(self):  # ''.join(reversed('ereh gub'))
            if randint(0, 1000) % 67 != 0:
                return object.__getattribute__(self, attr)
            raise AttributeError(f"{type(self).__name__} has no attribute: '{attr}'")
    

    写 bug 2 -- build-in function:

    思路:

    • len = 9
    • str = 'abc'

    暂时想不到一个“短路运算”的好例子;有缘再更。

    str 用在捕获异常,调用 str(e) 也是个不错的例子;有缘再更。


    写 bug 3 -- 默认参数+全局变量

    def func(param1, default_param=[]):
        pass
    

    想到好例子再更;


    ======

    感觉还是用 C 语言写 bug 好写一些;

    弄个野指针,bug 可以出现地纯洁的像一朵白莲花。

    ======

    抛砖引玉;有没有什么诡异的 Python bug 代码拿出来晒晒?

    5 条回复    2020-09-23 18:52:48 +08:00
    N1ckl32
        1
    N1ckl32  
       2020-09-23 00:17:22 +08:00
    追更
    no1xsyzy
        2
    no1xsyzy  
       2020-09-23 04:03:47 +08:00
    就 bug 1 来说,你没用 super()
    这在多继承的情况下会发生 bug
    比如接下来
    . class Mama:
    . def __getattribute__(self, attr):
    . return object.__getattribute__(self, attr)
    . class Erzi(Mama, Baba):
    . pass
    你这个 Baba 就没用咯。
    no1xsyzy
        3
    no1xsyzy  
       2020-09-23 04:04:46 +08:00   ❤️ 1
    @no1xsyzy 啊 . 不能保持空格,改改
    class Mama:
    ....def __getattribute__(self, attr):
    ........return object.__getattribute__(self, attr)
    class Erzi(Mama, Baba):
    ....pass
    oahebky
        4
    oahebky  
    OP
       2020-09-23 18:50:10 +08:00
    @no1xsyzy

    有道理。写的时候「大脑没有其它空间」考虑这个问题。
    oahebky
        5
    oahebky  
    OP
       2020-09-23 18:52:48 +08:00
    ## 写 bug 4 - str 的可迭代特性;没有 ensure

    具体代码就先不写了,因为「偶尔发生」+「合理」的例子不容易想;


    信息都在这个 bug 4 标题里面了。

    具体例子有缘再更新。

    ------
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2943 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:31 · PVG 08:31 · LAX 17:31 · JFK 20:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.