Initializing classes in a module for a namespace

There is a module car.py.

There is an engine and tires, and I want them (their methods and properties) to be available as

car.engine.data
# and
car.tires.data

So the file parts.pylooks like

class engineClass(object):
    def __init__(self):
        self.data = 'foo data 1'

class tiresClass(object):
    def __init__(self):
        self.data = 'foo data 2'

engine = engineClass()
tires = tiresClass()

And now after import carI can access them, because I want to -car.engine.data

Is this the right thing to do for this task?

+3
source share
1 answer

Of course ... I'm not quite sure what you are asking ...

There is nothing wrong with what you do, but you can skip class initialization if you showed. Just do:

class type1(object):
    data = 'foo 1'

class type2(object):
    data = 'foo 2'

Regardless of whether this makes sense in the context of what you are doing, I have no idea ...

In this case, you can simply do

class Container(object):
    pass

type1, type2 = Container(), Container()
type1.data = 'foo 1'
type2.data = 'foo 2'

Or any other number of similar things ... What do type1and type2represent?

+3
source

All Articles