0

What is the pythonic way to handle large objects? In my example I could have one big class creating one instance with many attributes or I could group some of them together (See class Car and class Motor):

class Car(object):

    color = "red"

    def __init__(self, num_wheels):
        self.burst = Motor(self)
        self.wheels = num_wheels
        for i in range(self.wheels):
            setattr(self, "wheel{}".format(i), Wheel(self, i))

    def _query(self, value):
        print "Get Serial Data: {}".format(value)


class Motor(object):  # Object is loaded only once in Car instance

    def __init__(self, top):
        self._top = top

    def temperature(self):
        return self._top._query("GET MOTOR TEMP")

    def rpm(self):
        return self._top._query("GET MOTOR RPM")


class Wheel(object):  # Object could be loaded many times in Car instance

    def __init__(self, top, number):
        self._top = top
        self._number = number

    def temperature(self):
        return self._top._query("GET WHEEL TEMP {}".format(self._number))

    def rpm(self):
        return self._top._query("GET WHEEL RPM {}".format(self._number))

I think this even makes more sense, when the Car has more than one wheel, as I could add more wheels.

But since Motor is never used more than once and never used else where, is it better style to put them into the Car class:

class Car(object):

    color = "red"

    def __init__(self, num_wheels):
        # Add wheels or other stuff

    def _query(self, value):
        print "Get Serial Data: {}".format(value)


    def motor_temperature(self):
        return self._query("GET MOTOR TEMP")

    def motor_rpm(self):
        return self.._query("GET MOTOR RPM")

I will have to access Car._query() from the Wheel and/or Motor class and my real life object contains about 40 attributes and methods I could group in 4-5 sub instances. Couldn't find much on this topic on the web.

Wolf82
  • 23
  • 6

1 Answers1

0

If you use large numbers of instances, you can used slots to reduce memory footprint.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103