sub typing built in type with common attributes. Am I right?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • King

    #1

    sub typing built in type with common attributes. Am I right?

    I am new to python and getting into classes. Here I am trying to
    create subtype of built in types with some additional attributes and
    function. 'Attributes' is the main class and holds all the common
    attributes that requires by these subtypes. This is what I came out
    with. I need to know whether everything is right here ? or there are
    some better ways to do it.

    class Attribute(objec t):
    """
    Common attributes and methods for custom types
    """

    def __init__(self, name=None, type=None, range=None, label=None):

    #read only attributes
    self._name = name
    self._type = type
    self._range = range

    #read/write attribute
    self.label = label

    #make read only attributes
    name = property(lambda self: self._name)
    type = property(lambda self: self._type)
    range = property(lambda self: self._range)

    class Float(float, Attribute):

    '''Custom Float class with some additional attributes.'''

    __slots__ = ['_Attribute__na me', '_Attribute__ty pe',
    '_Attribute__ra nge', 'label']

    def __new__(cls, value=0.0, *args, **kwargs):
    return float.__new__(c ls, value)

    def __init__(self, value=0.0, name=None, label=None, type=None,
    range=(0.0, 1.0)):
    super(Float, self).__init__( name=name, label=label, type=type,
    range=range)

    def __str__(self):
    return '{ %s }' % (float.__str__( self))

    class Int(int, Attribute):

    '''Custom Int class with some additional attributes.'''

    __slots__ = ['_Attribute__na me', '_Attribute__ty pe',
    '_Attribute__ra nge', 'label']

    def __new__(cls, value=0.0, *args, **kwargs):
    return int.__new__(cls , value)

    def __init__(self, value=0.0, name=None, label=None, type=None,
    range=(0.0, 1.0)):
    super(Int, self).__init__( name=name, label=label, type=type,
    range=range)

    def __str__(self):
    return '{ %s }' % (int.__str__(se lf))
  • Peter Otten

    #2
    Re: sub typing built in type with common attributes. Am I right?

    King wrote:
    I am new to python and getting into classes. Here I am trying to
    create subtype of built in types with some additional attributes and
    function. 'Attributes' is the main class and holds all the common
    attributes that requires by these subtypes. This is what I came out
    with. I need to know whether everything is right here ? or there are
    some better ways to do it.
    There may be some technical errors in your code, e. g.

    - the __slots__ look like a bit of bullshit: you already have a __dict__
    from the Attribute base class
    - name mangling is done for attributes starting with two underscores

    But the greater problem I see is that you are building up a huge bureaucracy
    where pythonic code would concentrate on a concrete goal with minimal
    administrative overhead.

    Peter

    Comment

    • King

      #3
      Re: sub typing built in type with common attributes. Am I right?

      My mistake...
      The correct __slots__ is like:
      __slots__ = ['_Attribute_nam e', '_Attribute_typ e', '_Attribute_ran ge',
      'label']

      Could you please suggest an alternative or code improvement for the
      matter.

      Prashant

      Comment

      • Peter Otten

        #4
        Re: sub typing built in type with common attributes. Am I right?

        King wrote:
        My mistake...
        The correct __slots__ is like:
        __slots__ = ['_Attribute_nam e', '_Attribute_typ e', '_Attribute_ran ge',
        'label']
        >
        Could you please suggest an alternative or code improvement for the
        matter.
        How about

        class AttributesMixin (object):
        """Warning: If you change name, type, or range of an existing object
        your computer will explode and you will have noone else to blame.
        """
        def __init__(self, name=None, type=None, range=None, label=None):
        self.name = name
        self.type = type
        self.range = range
        self.label = label

        class Float(float, AttributesMixin ): pass
        class Int(int, AttributesMixin ): pass

        Now go and write something useful :-)

        Peter

        Comment

        • Maric Michaud

          #5
          Re: sub typing built in type with common attributes. Am I right?

          Le Friday 18 July 2008 11:36:20 King, vous avez écrit :
          Could you please suggest an alternative or code improvement for the
          matter.
          I'm not sure what you are trying to achieve with your snippet, but I suspect
          it's some sort of templating, right ? If so, using the dynamic nature of
          python should help :
          >>>[103]: def make_subtype_wi th_attr(type_, ro_attr, rw_attr) :
          dic = {}
          for i in ro_attr : dic[i] = property(lambda s, n=i : getattr(s, '_'+n))
          def __new__(cls, *args, **kwargs) :
          instance = type_.__new__(c ls, *args)
          for i in rw_attr : setattr(instanc e, i, kwargs[i])
          for i in ro_attr : setattr(instanc e, '_'+i, ro_attr[i])
          return instance
          dic['__new__'] = __new__
          return type('my_' + type_.__name__, (type_,), dic)
          .....:
          >>>[113]: my_int = make_subtype_wi th_attr(int,
          {'name' : 'myint', 'id':123452}, ('foo',))
          >>>[114]: i = my_int(5, foo=3)
          >>>[115]: i.foo
          ...[115]: 3
          >>>[116]: i
          ...[116]: 5
          >>>[117]: i.id
          ...[117]: 123452
          >>>[118]: i.id = 2
          ---------------------------------------------------------------------------
          AttributeError Traceback (most recent call last)

          /home/maric/<ipython consolein <module>()

          AttributeError: can't set attribute


          --
          _____________

          Maric Michaud

          Comment

          • King

            #6
            Re: sub typing built in type with common attributes. Am I right?

            Thanks Michaud,

            You have actually solved an another problem by
            'make_subtype_w ith_attr' function.

            What actually I am trying to do here is to create custom types using
            built in types to use in my application.
            For example , float2, float3, color, vector, point, normal, matrix
            etc. The reason being creating as individual subtypes is because each
            subtypes has it's own set of functions as well as common functions and
            attributes defined in 'Attribute' class.

            Although I won't be doing any math using subtypes like multiply a
            color by another color or add a float and a color. One of the
            important function that every subtype has is to print itself in a
            special format. For 'color' it would be :

            'type' + 'name' + ' = color('+color[0]+', '+color[2]+',
            '+color[2]+');'
            Result: color myColor = color(0.5, 0.1, 1.0);

            I hope this will make things more clearer. If you do have any
            suggestions then please send it across.

            Prashant

            Comment

            Working...