Can Python collections hold objects?

person github

In Python, a collection ( set) can only contain objects of immutable type. This means that you cannot directly add mutable objects (such as lists or dictionaries) to the collection. However, you can add immutable objects such as integers, floats, strings, tuples, etc.

For example:

# 可以添加
my_set = set()
my_set.add(1)
my_set.add("hello")
my_set.add((1, 2, 3))

# 不能添加
# my_set.add([1, 2, 3])  # TypeError: unhashable type: 'list'
# my_set.add({"key": "value"})  # TypeError: unhashable type: 'dict'

If you need a data structure that is like a collection but can contain mutable objects, you may need to use a list or other data structure and manually manage uniqueness within it.

Additionally, custom objects can be added to the collection, provided they are immutable or the class defines __hash__()and __eq__()methods.

For example:

class MyClass:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        return hash(self.value)

    def __eq__(self, other):
        return self.value == other.value

obj1 = MyClass(1)
obj2 = MyClass(2)

my_set = set()
my_set.add(obj1)
my_set.add(obj2)

In this example, MyClassinstances of are hashable because we defined the __hash__()and __eq__()methods so they can be added to the collection.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/133527643