有没有办法从它的属性中获取对象?

时间:2021-01-22 14:17:28

标签: python oop

我想按属性列出对象,并仅使用列表中的属性获取它。

class foo:
    def __init__(self,id):
        self.id=id

a=foo(0)
b=foo(1)

ids=[a.id,b.id]

我可以在只有 a 的情况下引用 ids 吗?

如果这种方式不可能,我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用字典:

class foo:
    def __init__(self,id):
        self.id=id


a=foo(0)
b=foo(1)

ids={a.id:a, b.id:b}
print(ids[0])

没有字典的例子

注意:使用 Python 中的元编程可能会更好地实现这一点,并且您的问题在创建 Python 包、框架等时似乎可以在实际应用中使用。

尽管如此,它确实以一种笨拙的方式实现了这一点。

import random

class foo:
    def __init__(self,id):
        self.id=id


def create_counter():
    count = 0
    def internal():
        nonlocal count
        count += 1
        return count
    return internal

counter = create_counter()

def create_id():
    """Generate random id, uses a stateles Closure to keep track of counter"""

    id_ = None
    name = 'class_'
    id_gen = str(hex(random.randrange(1000)))       
    id_ =  name + str(counter()) + "_" + id_gen[2:]        

    return id_


def change_name_ref(inst_obj):
    """Change Instance Name to Instance ID"""
    inst_obj.__name__ = inst_obj.id



a = foo(create_id()) # --> Assign a radnom Id 
b = foo(create_id())
c = foo('class_1_15b')

change_name_ref(a)
change_name_ref(b)
change_name_ref(c)

ids = [a, b, c]


def get_instance(inst_list, target):
 
    for idx, id_ in enumerate(inst_list):
        if id_.__name__ == target:
            inst = inst_list[idx]
            print(f'Here The Class instance {inst}, ID: {inst.id}')


value = get_instance(ids, 'class_1_15b')

# Here The Class instance <__main__.foo object at 0x7f6988f016d0>, ID: class_1_15b