简体   繁体   中英

Is there a difference between Set and set?

I am using Python 2.7, and just wondering if there is any difference between set() and Set() (ie with/without the capitalization).

Specifically, the Python instructions https://docs.python.org/2/library/sets.html suggest that Sets should be imported and initialized as:

from sets import Set
x = Set()

I have just been using the command set() without importing anything, ie:

x = set()

Just wondering if these are identical, or if they are somehow different.

As it says in Python documentation the Set class provides every set method except for __hash__() .

For advanced applications requiring a hash method, the ImmutableSet class adds a hash () method but omits methods which alter the contents of the set. Both Set and ImmutableSet derive from BaseSet, an abstract class useful for determining whether something is a set: isinstance(obj, BaseSet).

I have no any deep knowledge on them - honestly until I saw your question, I thought that they were identical.

Now checked

>>> from sets import Set
>>> x = Set()
>>> y = set()
>>> len(dir(y))
54
>>> len(dir(x))
63

and realized that they have some dfferences

>>> Y = set(dir(y))
>>> X = set(dir(x))
>>> X-Y
set(['_compute_hash', '__module__', '_update', '_binary_sanity_check', '__setstate__', '__deepcopy__', '_repr', '__as_immutable__', 'union_update', '__slots__', '__copy__', '__as_temporarily_immutable__', '_data', '__getstate__'])    
>>> Y-X
set(['__rand__', '__ror__', '__rsub__', '__rxor__', 'isdisjoint'])

Ofcourse this doesn't give any clear information on their differences, but shows that they are not identical :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM