简体   繁体   中英

python: how to get an item from a set of custom class object

class Folder:
    def __init__(self, name):
        self.name = name
        self.items = []
    
    def __hash__(self):
        return hash(self.name)
    
    def __eq__(self, other):
        return self.name == other.name

Lets create some folders:

folder_1 = Folder('folder_1')
folder_1.items = ['a', 'b', 'c']


folder_2 = Folder('folder_2')
folder_3 = Folder('folder_3')

folders = set([folder_1, folder_2, folder_3])

Now what I want to do is to find a folder in a folders set and access its item property without changing the folders set.

folder_to_find = Folder('folder_1')

We can notice that folder_to_find == folder_1 is True with a difference that folder_1 has items property set and folder_to_find has not.

I can check folder_to_find like object exists in folders set with in operator but cannot get folder_1 with the help of folder_to_find so that I can access items property of folder_1 object.

My workaround would be to use python dictionary instead of set.

Still, is there any way we can achieve this with O(1)?

You can use a simple for loop or next with generator expression

folder = next((folder for folder in folders if folder == folder_to_find), None)

folder is a reference for folder_1 , you can get folder_1 data and edit it

folder.items[0] = 1
print(folder_1.items) # [1, 'b', 'c']

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