factory functions & methods

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Mar 11 06:55:48 CET 2009


En Sun, 08 Mar 2009 20:08:32 -0200, Aaron Brady <castironpi at gmail.com>  
escribió:

> Hello,
>
> I am creating a container.  I have some types which are built to be
> members of the container.  The members need to know which container
> they are in, as they call methods on it, such as finding other
> members.  I want help with the syntax to create the members.
> Currently, the container has to be a parameter to the instantiation
> methods.  I want the option to create members with attribute syntax
> instead.
>
> Currently, I have:
>
> cA= Container( )
> obA= SomeType( cA )
> obB= OtherType( cA, otherarg )
>
> I want:
>
> cA= Container( )
> obA= cA.SomeType( )
> obB= cA.OtherType( otherarg )
>
> What are my options?

What about this? Doesn't require any kind of registration - the Container  
just looks for any missing attribute in the global namespace.

py> from functools import partial
py>
py> class Container(object):
...   def __init__(self):
...     self.items = []
...   def add(self, item):
...     self.items.append(item)
...   def __getattr__(self, name):
...     if name in globals():
...       return partial(globals()[name], self)
...
py> class SomeType(object):
...   def __init__(self, parent):
...     self.parent = parent
...     self.parent.add(self)
...
py> class OtherType(SomeType):
...   def __init__(self, parent, arg):
...     SomeType.__init__(self, parent)
...     self.x = arg
...
py> cA = Container()
py> obA = cA.SomeType()
py> obB = cA.OtherType(5)
py> print cA.items
[<__main__.SomeType object at 0x00B9E4B0>, <__main__.OtherType object at  
0x00B9E890>]

> P.S.  The container and members are C extension types, not pure Python.

It's all implemented in __getattr__, so it should be easy to write the  
equivalent C code. (I really don't know if __getattr__ maps to any  
predefined slot in the type structure, or what)

-- 
Gabriel Genellina




More information about the Python-list mailing list