factory functions & methods
Aaron Brady
castironpi at gmail.com
Mon Mar 9 09:38:50 EDT 2009
On Mar 8, 5:45 pm, "andrew cooke" <and... at acooke.org> wrote:
> Aaron Brady wrote:
> > 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?
>
> maybe there'sa simpler way, but i think this is what you want, if the
> container is the first arg to the other constructors:
>
> >>> def foo(x):
>
> ... print x
> ...>>> from types import MethodType
> >>> class Bar:
>
> ... def __init__(self):
> ... self.foo = MethodType(foo, self)
> ...>>> b = Bar()
> >>> b.foo()
>
> <__main__.Bar instance at 0x7f35edb091b8>
>
> above is with 3.0. for some odd reason i thing the order of teh args to
> MethodType may have changed recently, so be careful.
>
> andrew
>
>
>
> > P.S. The container and members are C extension types, not pure Python.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>
I was thinking that it was a job for '__get__'. (3.0.1.)
>>> class B( type ):
... def __get__( self, instance, owner ):
... print( self, instance, owner )
...
>>> class BB( metaclass= B ):
... pass
...
>>> class C:
... memB= BB
...
>>> C.memB
<class '__main__.BB'> None <class '__main__.C'>
>>> C().memB
<class '__main__.BB'> <__main__.C object at 0x00BA2290> <class
'__main__.C'>
So, from above:
cA= Container( )
obA= cA.SomeType( )
obB= cA.OtherType( otherarg )
I would need 'Sometype' and 'Othertype' to be instances of a metatype,
which is the part that concerns me. If it worked, 'Container' could
look like this:
class Container:
SomeType= BoundFirst( SomeType )
OtherType= BoundFirst( OtherType )
It looks like it has a prayer. But how hard will it be in C?
More information about the Python-list
mailing list