factory functions & methods

Piet van Oostrum piet at cs.uu.nl
Wed Mar 11 13:52:11 EDT 2009


>>>>> Aaron Brady <castironpi at gmail.com> (AB) wrote:

>AB> Hello,
>AB> I am creating a container.  I have some types which are built to be
>AB> members of the container.  The members need to know which container
>AB> they are in, as they call methods on it, such as finding other
>AB> members.  I want help with the syntax to create the members.
>AB> Currently, the container has to be a parameter to the instantiation
>AB> methods.  I want the option to create members with attribute syntax
>AB> instead.

>AB> Currently, I have:

>AB> cA= Container( )
>AB> obA= SomeType( cA )
>AB> obB= OtherType( cA, otherarg )

>AB> I want:

>AB> cA= Container( )
>AB> obA= cA.SomeType( )
>AB> obB= cA.OtherType( otherarg )

>AB> What are my options?

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

You could do something like this (translated to C)

class Container(object):
  def __init__(self):
    self.items = []
  def add(self, item):
    self.items.append(item)
  def SomeType(self):
      newobj = SomeType()
      self.add(newobj)
  def OtherType(self, arg):
      newobj = OtherType(arg)
      self.add(newobj)
  
class SomeType(object):
  def __init__(self):
      pass
  
class OtherType(SomeType):
  def __init__(self, arg):
    SomeType.__init__(self)
    self.x = arg

cA = Container()
obA = cA.SomeType()
obB = cA.OtherType(5)
print cA.items

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list