473,583 Members | 2,785 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dictionary with object's method as thier items

Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
etc..
thanks

Aug 30 '06 #1
7 2062
On 30 Aug 2006 06:35:17 -0700
"noro" <am******@gmail .comwrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
etc..

Sure. But the syntax would be:
d['function one'] = c.func1
d['function one']()

I'm not sure what this gets you but it works.

John Purser

Aug 30 '06 #2
noro wrote:
Is it possible to do the following:

for a certain class:
[...]
by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C
Something like this?
>>class C:
.... def f1(self):
.... print "i'm one"
.... def f2(self):
.... print "i'm two"
....
>>obj = C()
d = {'one': obj.f1, 'two': obj.f2}
d['one']()
i'm one
>>d['two']()
i'm two

--
Roberto Bonvallet
Aug 30 '06 #3
noro wrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
etc..
Let me guess... What you want to is in fact to call a method by it's
name ? If so, getattr(obj, name) is your friend:

class Knight(object):
def __init__(self):
self._saywhat = "ni"
self._wantwhat ="shrubbery"

def says(self):
return self._saywhat

def wants(self):
return self._wantwhat

k = Knight()

print getattr(k, "says")()
print getattr(k, "wants")()

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Aug 30 '06 #4
noro wrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}
Perhaps this:
>>class C:
.... def function(self, arg):
.... print arg
....
>>obj = C()
d = C.__dict__
d['function'](obj, 42)
42
>>>

Georg
Aug 30 '06 #5
At Wednesday 30/8/2006 10:35, noro wrote:
>for a certain class:
by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

and so i could access every method of instances of C, such as obj with
sometiing like:
(i know that this syntax wont work )

obj.(d['function one'])
obj.(d['function two'])
You can use dir(obj) to get its list of attributes (including method
names) then use getattr to invoke the method.

methodname='fun c1'
getattr(obj,met hodname)()

See the inspect module too.
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 30 '06 #6
great that is what i looked for.
>>class C:
... def function(self, arg):
... print arg
...
>>obj = C()
>>d = C.__dict__
>>d['function'](obj, 42)
42
this allows me the access the same method in a range of objects.

i can put all the functions i need in a dictionary as items, and the
vars as keys, and then call them for all objects that belong to a
class..

something like this

----------------------------------------------------
class C:

#object vars
self.my_voice
self.my_size
self.my_feel

# a method that do somthing, that might give different result for
different objects
getVoice(self):
return(self.my_ voice+'WOW')

getSize(self):
return(self.my_ size*100)

getFeel(self):
return(self.my_ feel)
#create the dictionary with a reference to the class methode
dic={'voice':C. getVoice,'size' :C.getSize,'fee l':C.getFeel}
# create array of 10 different objects
cArray = []
for i in range(10)
cArray.append(C ())
cArray[0].my_size=i

# choose the function you need, and get the result
choice=WHAT EVER KEY (e.g 'size')
for i in range(10)
print dic[choice](cArray[i])

#or even print all the values of all objects. if i ever want to print
diffenet valuse i only need
# to change the dictionary, nothing else...
for choice in dic:
for i in range(10)
print dic[choice](cArray[i])
---------------------------------------------------------------
i totaly forget about the "self" argument in every method...

a. is the main reason "self is there, or is it only a side effect?
b. what do you think about this code style? it is not very OOP, but i
cant see how one can do it other wise, and be able to control the
function printed out with something as easy as dictionary..

Georg Brandl wrote:
noro wrote:
Is it possible to do the following:

for a certain class:

----------------------------
class C:

def func1(self):
pass
def func2(self):
pass
def func4(self):
pass

obj=C()
----------------------------

by some way create a dictionary that look somthing like that:

d= {'function one': <reference to C.func1()>, \
'function two': <reference to C.func2()>, \
'function three': <reference to C.func3()>}

Perhaps this:
>>class C:
... def function(self, arg):
... print arg
...
>>obj = C()
>>d = C.__dict__
>>d['function'](obj, 42)
42
>>>


Georg
Aug 30 '06 #7
noro wrote:
great that is what i looked for.
Hmmm... Not quite sure
>>>class C:
... def function(self, arg):
... print arg
...
> >>obj = C()
d = C.__dict__
d['function'](obj, 42)
42

this allows me the access the same method in a range of objects.
class Obj(object):
def __init__(self, num):
self.num = num
def method(self):
return "in %s.method" % self

for obj in [Obj(i) for i in range(10)]:
print getattr(obj, "method")()

i can put all the functions i need in a dictionary as items, and the
vars as keys, and then call them for all objects that belong to a
class..

something like this

----------------------------------------------------
class C:

#object vars
self.my_voice
self.my_size
self.my_feel

# a method that do somthing, that might give different result for
different objects
getVoice(self):
return(self.my_ voice+'WOW')

getSize(self):
return(self.my_ size*100)

getFeel(self):
return(self.my_ feel)
#create the dictionary with a reference to the class methode
dic={'voice':C. getVoice,'size' :C.getSize,'fee l':C.getFeel}
# create array of 10 different objects
cArray = []
for i in range(10)
cArray.append(C ())
cArray[0].my_size=i

# choose the function you need, and get the result
choice=WHAT EVER KEY (e.g 'size')
for i in range(10)
print dic[choice](cArray[i])

#or even print all the values of all objects. if i ever want to print
diffenet valuse i only need
# to change the dictionary, nothing else...
for choice in dic:
for i in range(10)
print dic[choice](cArray[i])
---------------------------------------------------------------
i totaly forget about the "self" argument in every method...
???
a. is the main reason "self is there, or is it only a side effect?
I'm not sure I understand your question.
b. what do you think about this code style?
Don't ask me if you don't want to get hurt !-)
it is not very OOP,
This is not a problem - Python doesn't forces you that much into OO.
but i
cant see how one can do it other wise,
using getattr(<object >, <attrname>[,<default>])
and be able to control the
function printed out with something as easy as dictionary..
Here's a somewhat more pythonic way to do the same thing (NB : not tested):

# a simple decorator
def choice(func):
func.is_choice = True
return func

# helper func
def is_choice(obj):
return callable(obj) and getattr(obj, 'is_choice', False)

# braindead metaclass
class ChoicesMeta(typ e):
def __init__(cls, name, bases, classdict):
cls.choices = [name for name, attrib in classdict.items () \
if is_choice(attri b)]

# our class...
class Foo(object):
__metaclass__ = ChoicesMeta

def __init__(self, num):
self.num = num

# mark the method as usable in choices
@choice
def bar(self):
return "foo #%s.bar" % self.num

@choice
def baaz(self):
return "foo #%s.baaz" % self.num

# let's test:
foos = [Foo(i) for i in range(10)]

choice = <whatever name existing in Foo.choices>
for foo in foos:
print getattr(foo, choice)()
HTH

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Aug 30 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3578
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary...
4
2510
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone.
1
1549
by: greg | last post by:
Hi I referenced in COM Dictionary object (like Scripting Dictionary) It has Items method that returns object What should I cast it to??? some collection? Ideas? SRSPLUSLib.SrsClass srs = new SRSPLUSLib.SrsClass(); srs.Startup();
2
3412
by: jg | last post by:
I was trying to get custom dictionary class that can store generic or string; So I started with the example given by the visual studio 2005 c# online help for simpledictionay object That seem to miss a few things including #endregion directive and the ending class } Is there not a simple way like in dotnet vb? I managed to get the...
90
10754
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
3
4087
by: Mark Rae | last post by:
Hi, Is it possible to use a Dictionary<int, stringor even Dictionary<string, stringas the DataSource for a DropDownList directly, i.e. without having to iterate through the the Dictionary's KeyValuePair collection and populate the DropDownList's Items collection manually? The DropDownList certainly "understands" the Dictionary object, but...
5
1943
by: Bill Jackson | last post by:
What is the benefit of clearing a dictionary, when you can just reassign it as empty? Similarly, suppose I generate a new dictionary b, and need to have it accessible from a. What is the best method, under which circumstances? .... a = b
5
6316
by: davenet | last post by:
Hi, I'm new to Python and working on a school assignment. I have setup a dictionary where the keys point to an object. Each object has two member variables. I need to find the smallest value contained in this group of objects. The objects are defined as follows:
3
1486
by: mk | last post by:
Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): .... return "f2 " + arg .... .... return "f1" + arg ....
0
7897
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7829
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7940
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5705
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3824
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3850
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1438
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.