python - 能不能给个null object pattern 这个模式的应用实例
黄舟
黄舟 2017-04-17 13:00:59
[Python讨论组]

null object python是一个设计模式,python实现如下,此模式是想减少无必要的is null逻辑判断,不过没能想到具体怎么应用在项目或者自己的代码中,希望有个应用的实例代码,thanks。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""http://code.activestate.com/recipes/68205-null-object-design-pattern/"""


class Null:

    def __init__(self, *args, **kwargs):
        """Ignore parameters."""
        return None

    def __call__(self, *args, **kwargs):
        """Ignore method calls."""
        return self

    def __getattr__(self, mname):
        """Ignore attribute requests."""
        return self

    def __setattr__(self, name, value):
        """Ignore attribute setting."""
        return self

    def __delattr__(self, name):
        """Ignore deleting attributes."""
        return self

    def __repr__(self):
        """Return a string representation."""
        return "<Null>"

    def __str__(self):
        """Convert to a string and return it."""
        return "Null"


def test():
    """Perform some decent tests, or rather: demos."""

    # constructing and calling

    n = Null()
    print(n)

    n = Null('value')
    print(n)

    n = Null('value', param='value')
    print(n)

    n()
    n('value')
    n('value', param='value')
    print(n)

    # attribute handling

    n.attr1
    print('attr1', n.attr1)
    n.attr1.attr2
    n.method1()
    n.method1().method2()
    n.method('value')
    n.method(param='value')
    n.method('value', param='value')
    n.attr1.method1()
    n.method1().attr1

    n.attr1 = 'value'
    n.attr1.attr2 = 'value'

    del n.attr1
    del n.attr1.attr2.attr3

    # representation and conversion to a string

    assert repr(n) == '<Null>'
    assert str(n) == 'Null'


if __name__ == '__main__':
    test()

### OUTPUT ###
# Null
# Null
# Null
# Null
# attr1 Null
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号