Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a little wrapper class for FooB's to mimic FooA's, but still retain their FooB-ishness.</p> <pre><code>from collections import namedtuple # use namedtuple to define some simple classes (requires Py2.6 or later) FooA = namedtuple('FooA', 'id name type foo') FooB = namedtuple('FooB', 'idfoo namefoo spam') # create a wrapper class for FooB's to look like a FooA class FooAMimic(object): attrMap = dict(zip(FooA._fields, FooB._fields)) # or if the fields aren't nicely ordered, declare this mapping explicitly #~ attrMap = { 'id' : 'idfoo', 'name' : 'namefoo', 'foo' : 'spam' } def __init__(self, obj): self.obj = obj def __getattr__(self, aname): ob = self.obj if aname in self.attrMap: return getattr(ob, self.attrMap[aname]) elif hasattr(ob, aname): return getattr(ob, aname) else: raise AttributeError("no such attribute " + aname) def __dir__(self): return sorted(set(dir(super(FooAMimic,self)) + dir(self.obj) + list(FooA._fields))) </code></pre> <p>Use it like this:</p> <pre><code># make some objects, some FooA, some FooB fa = FooA('a', 'b', 'c','d') fb = FooB('xx', 'yy', 'zz') fc = FooA('e', 'f', 'g','h') # create list of items that are FooA's, or FooA lookalikes coll = [fa, FooAMimic(fb), fc] # access objects like FooA's, but notice that the wrapped FooB # attributes are still available too for f in sorted(coll, key=lambda k : k.id): print f.id, '=', try: print f.namefoo, "(really a namefoo)" except AttributeError: print f.name </code></pre> <p>Prints:</p> <pre><code>a = b e = f xx = yy (really a namefoo) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload