Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

python - is there any way to get the object from its property?

I want to list the objects by its attribute, and get it with only the attributes that is in the list.

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

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

ids=[a.id,b.id]

can I refer to a with only having ids ?

and if it is not possible this way, how can I ?

question from:https://stackoverflow.com/questions/65846862/is-there-any-way-to-get-the-object-from-its-property

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

User a dictionary:

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])

An example without a dictionary

NOTE: This may be better achieved using a Meta-programming in Python, and your question may seem that can have an actual real world usage when creating Python Packages, Frameworks etc.

Still, in a clumsy way it does achieve this.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...