factory functions & methods

andrew cooke andrew at acooke.org
Sun Mar 8 18:45:29 EDT 2009


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
>
>





More information about the Python-list mailing list