Re: Dynamically determine base classes on instantiation

Discussion in 'Python' started by MRAB, Aug 15, 2012.

  1. MRAB

    MRAB Guest

    On 15/08/2012 22:17, Thomas Bach wrote:
    > Hi list,
    >
    > I'm confronted with a strang problem I cannot find a clean solution
    > for. To me it seems like I need meta-classes. Anyway, I stucked a bit
    > deeper in that topic and couldn't find a proper solution neither. But,
    > judge for yourselve.
    >
    > I want a class that determines on instantiating its base classes
    > dynamically. Consider the following two use cases
    >
    > a = Foo(['a', 'list']) # returns an instance that behaves like a list
    > assert len(a) == 2
    > assert a[0] == 'a'
    > assert a == ['a', 'list']
    > assert isinstance(a, list) # This would be nice, but no must-have
    >
    > b = Foo({'blah': 8}) # returns an instance that behaves like a dict
    > assert b['blah'] == 'blah'
    > assert b == {'blah': 8}
    > assert isinstance(b, dict) # again, no must-have
    >
    > a.do_something() # common function to both instances as defined
    > b.do_something() # in the Foo class
    >
    >
    > What I'm currently doing something like the following:
    >
    > class Foo(object):
    >
    > def __init__(self, obj):
    > self._obj = obj
    >
    > def __len__(self):
    > return len(self._obj)
    >
    > def __getitem__(self, name):
    > return self._obj[name]
    >
    > # …
    >
    > def do_something(self):
    > # do something on self._obj
    > pass
    >
    > Which seems ugly. Is there a way to provide the functions of `list'
    > and `dict' in Foo's look-up path without having to write all the
    > stubs myself?
    >

    Does Foo have to be a class? Couldn't it just be a factory function?
     
    MRAB, Aug 15, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guoqi Zheng

    dynamically determine the base href value

    Guoqi Zheng, Jan 13, 2005, in forum: ASP .Net
    Replies:
    3
    Views:
    673
    Karl Seguin
    Jan 13, 2005
  2. Rogan Dawes
    Replies:
    4
    Views:
    287
    Chris Smith
    Jan 23, 2005
  3. Colin Goudie
    Replies:
    6
    Views:
    483
    Victor Bazarov
    Jan 26, 2004
  4. Replies:
    1
    Views:
    587
    Salt_Peter
    Dec 25, 2006
  5. Thomas Bach
    Replies:
    18
    Views:
    382
    Mark Lawrence
    Aug 18, 2012
Loading...

Share This Page