Need a help

4 views
Skip to first unread message

Deepak Pant

unread,
Mar 16, 2012, 1:40:07 AM3/16/12
to foss-...@googlegroups.com
Hello Foss Python Community,
           I have a query
        
Class User:
     def __init__(self):
            self.name=''
            self.id=''
     def setuser(self,name,id):
            self.name=name
            self.id=id


User().setuser('deepak',5)
User().setuser('munna',6)
User().setuser('howday',9)


is there any easier solution i can return objects id that matches name
say as

for u in User:
    if(u.name=='deepak'):
        print u.id

I need to find out objects that matches attributes
Need to solve this problem Thanks in advance


Regards
Deepak Pant
in...@xnimbus.net

Lava Kafle

unread,
Mar 16, 2012, 2:16:52 AM3/16/12
to foss-...@googlegroups.com
Hashmap !!!!
Lava Kafle
Ms by Research in Computer Science 
Kathmandu University
cell: 
9841224387
9801034557






Kailash Budhathoki

unread,
Mar 17, 2012, 2:13:07 AM3/17/12
to foss-...@googlegroups.com
Hi Deepak, 


Your requirement seems interesting. Without asking much more about your intention, you can use weakrefs to keep track of the references.

Here's a sample code for your requirement;


from collections import defaultdict
import weakref

_ref_tracker = defaultdict(list)
class TrackRefs(object):
    def __init__(self):
        _ref_tracker[self.__class__].append(weakref.ref(self))
    def get_objs(self):
        for ref in _ref_tracker[self.__class__]:
            if ref():
                yield ref()

class User(TrackRefs):
    def __init__(self, name, id):
        super(User, self).__init__()
        self.name = name
        self.id = id

user1 = User('Harke', 6)
user2 = User('Birkhe', 9)
user3 = User('Chyante', 69)

for obj in User("", "").get_objs(): #remember i am using an extra object here   
    if obj.name == 'Chyante':
        print obj.id 

You could have easily used default dictionary class in python to keep track of username and ids easily. I would rather use a simple dictionary as a member variable than keep track of object references ;) .

--
Kailash Budhathoki
Reply all
Reply to author
Forward
0 new messages