代码之家  ›  专栏  ›  技术社区  ›  Mark Storer

无和<no value>

  •  2
  • Mark Storer  · 技术社区  · 5 年前

    null C++的 nullptr None 看起来非常像Python版本的老主题。

    然后我看到了这个函数声明:

     numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
    

    两者有什么区别 没有 <no value>

    1 回复  |  直到 5 年前
        1
  •  5
  •   Martijn Pieters    5 年前

    在Python本身中 .

    考虑到这一点 None 也是有效对象 . 有时候你想接受 作为参数的有效值,因此不能将其用作可选参数的默认值。你无法区分默认的 有人路过 没有 很明显,因为它是一个独生子!

    单身哨兵。您可以从任何东西创建一个,但最简单的是使用 object() 实例:

    _sentinel = object()
    
    def foo(bar, baz=_sentinel):
        if baz is not _sentinel:
            # baz has a defined value, because it is
            # not a reference to the sentinel
    

    <no value> 在文件中表明 baz [...] 例如,围绕可选参数。

    numpy.amin() numpy.minimum() (通过 ufunc.reduce() ,或, 如果第一个参数是实现 amin() ,到子类的方法。因为后者应该能够设置自己的默认值,所以使用sentinel可以让 阿明() 实现只传递那些实际给定了显式值的关键字参数,而不指定子类的类型 .amin()

    Numpy项目 created their own singleton class to act as a sentinel 所以他们可以给这个物体一个有用的 repr() 输出:

    >>> from numpy._globals import _NoValue
    >>> _NoValue
    <no value>
    >>> type(_NoValue)
    <class 'numpy._globals._NoValueType'>
    

    最后, 没有 与…相比 null nullptr . 没有 是一个单例对象,是要引用的对象,而不是另一个对象。 空PTR 用于向 ,并且可以像其他标量值一样传递。在Python中不能这样做,因为所有内容都是对对象的有效引用。(最多,你会得到一个 NameError UnboundLocal 如果尝试使用尚未绑定到其命名空间中的名称,则出现异常)。

        2
  •  0
  •   hpaulj    5 年前

    的代码 np._NoValue

    class _NoValueType(object):
        """Special keyword value.
    
        The instance of this class may be used as the default value assigned to a
        deprecated keyword in order to check if it has been given a user defined
        value.
        """
        __instance = None
        def __new__(cls):
            # ensure that only one instance exists
            if not cls.__instance:
                cls.__instance = super(_NoValueType, cls).__new__(cls)
            return cls.__instance
    
        # needed for python 2 to preserve identity through a pickle
        def __reduce__(self):
            return (self.__class__, ())
    
        def __repr__(self):
            return "<no value>"
    File:           /usr/local/lib/python3.6/dist-packages/numpy/_globals.py
    Type:           type