Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #36916 > unrolled thread

Re: cymbalic reference?

Started byrh <richard_hubbe11@lavabit.com>
First post2013-01-16 13:06 -0800
Last post2013-01-16 13:06 -0800
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: cymbalic reference? rh <richard_hubbe11@lavabit.com> - 2013-01-16 13:06 -0800

#36916 — Re: cymbalic reference?

Fromrh <richard_hubbe11@lavabit.com>
Date2013-01-16 13:06 -0800
SubjectRe: cymbalic reference?
Message-ID<mailman.581.1358370409.2939.python-list@python.org>
On Tue, 15 Jan 2013 21:08:02 -0800
Benjamin Kaplan <benjamin.kaplan@case.edu> wrote:

> On Tue, Jan 15, 2013 at 8:56 PM, rh <richard_hubbe11@lavabit.com>
> wrote:
> > I have this working and I am curious to know how others do same.
> >
> > class Abc(object):
> >     def __init__(self):
> >         pass
> >     def good(self):
> >         print "Abc good"
> >     def better(self):
> >         print "Abc better"
> >
> > urls = {'Abc':'http://example.com'}
> > strings = ['good', 'better']
> >
> > for s in urls:
> >     o = eval("%s()" % s)
> >     for string in strings:
> >         eval("o.%s()" % string)
> >
> >
> > Yes, 'spose symbolic references is what these are....
> >
> > While I'm at it what magic could I use to print "the-class-I-am-in
> > good" instead of hard-coding "Abc good"? I tried __class_ and
> > self.__class__
> >
> > --
> 
> Rather than using eval, you can grab the class out of globals(), and
> then use getattr to get the methods.
> 
> >>> for s in urls :
> ...     o = globals()[s]()
> ...     for method in strings :
> ...         getattr(o, method)()
> ...
> Abc good
> Abc better
> 
> And for getting the class name, the class has a __name__ attribute. So
> you could use self.__class__.__name__.

My final product uses your suggestions along with one from the other post.
I like the idea of storing the class name as the key.  Then no call to globals()
is needed.  But I still have to test how that object behaves when it's a key.
i.e. Is it deeply bound? Shallow? Tight? Loose? Not sure which is the correct
term! So maybe I want {Abc:'http://example.com'} and o = s() instead.

And a small change to the class.

class Abc(object):
    def __init__(self):
        self.me = self.__class__.__name__
    def good(self):
        print self.me, "good"
    def better(self):
        print  self.me, "better"

urls = {Abc():'http://example.com'}
strings = ['good', 'better']

for s in urls:
    o = s
    for method in strings:
        getattr(o, method)()


-- 

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web