Question

I know you can do, for example:

class Node(object):
   __slots__ = 'data', 'left', 'right'

   def __init__(self, data=None, left=None, right=None):
      self.data  = data
      self.left  = left
      self.right = right

But how can I do something in order to get, for example:

class Node(object):
   __slots__ = 'data', 'left', 'right'
   data.struct = 'hour', 'min', 'day'

   def __init__(self, data=None, left=None, right=None):
      self.data  = data
      self.left  = left
      self.right = right
      self.data.hour = hour
      self.data.min = min
      self.data.day = day

I know that syntax is not right, but I hope you can get the idea.

Was it helpful?

Solution

You need to define class for data, that contains members hours, min, day. You can use it convenient factory collections.namedtuple for basic use:

#!/usr/bin/env python

import collections

Time_tuple = collections.namedtuple("Time", ['hour', 'min', 'day'])


class Node(object):
    def __init__(self, time=(None, None, None)):
        self.time = Time_tuple(*time)

node = Node()
print repr(node.time.day)

other_node = Node((23, 50, 1))
print other_node.time.hour

Please note, that this gives you no control about if values passed to constructor are valid. If you would like to add check like this, you should write your own Time_tuple class, and raise ValueError if data is incorrect (e.g. hour is 42).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top