python set add方法

python 集合set


class set(object):
    def add(self, *args, **kwargs):  
    
 
源代码里面,add方法,参数写的是*args,不是应该可以可以传递多个值的吗

ss = {1,3,5}
ss.add(7,9)  为什么会出错呢!!!??
阅读 3.8k
2 个回答

你和我看的不是一份源码(lib\sets.py)?

class Set(BaseSet):
    def add(self, element):
        """Add an element to a set.

        This has no effect if the element is already present.
        """
        try:
            self._data[element] = True
        except TypeError:
            transform = getattr(element, "__as_immutable__", None)
            if transform is None:
                raise # re-raise the TypeError exception we caught
            self._data[transform()] = True

集合的实现部分是 C 语言实现的,不知道你们找的 "源码" 究竟是哪里看的,一些IDE为了提示友好是会做一些声明工作的如 PyCharm。题主应该只是想追究 add 中参数是怎么声明的吧。这部分在 setobject.c 中可以看关于 set 对象的属性方法:

static PyMethodDef set_methods[] = {
    {"add",             (PyCFunction)set_add,           METH_O, add_doc},
    {"clear",           (PyCFunction)set_clear,         METH_NOARGS, clear_doc},
    {"difference",      (PyCFunction)set_difference_multi,      METH_VARARGS, difference_doc},
    ...
}

set.add 的实现部分就是 set_add 了,可以看下它的声明:

static PyObject *
set_add(PySetObject *so, PyObject *key)
{
    if (set_add_key(so, key))
        return NULL;
    Py_RETURN_NONE;
}

只有一个参数哦~也就是说它只能单个元素添加。

另外,这部分你可以通过 python 内置的帮助函数 help() 来看它的说明:

>>> help(set.add)
Help on method_descriptor:

add(...)
    Add an element to a set.

    This has no effect if the element is already present.

>>>

代码出处:https://github.com/python/cpy...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题