Qiao
Qiao

Reputation: 17049

Initializing classes in module for namespace

There is a module car.py.

There are engine and tires, and I want them (theirs methods and properties) to be accessible as

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

So file parts.py looks 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 car I can access them as I want - car.engine.data

Is it a right thing to do for this task?

Upvotes: 3

Views: 121

Answers (1)

Joe Kington
Joe Kington

Reputation: 284582

Sure... I'm not quite sure what you're asking...

There's nothing wrong with what you're doing, but you could skip initializing the classes in the case you've shown. Just do:

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

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

Whether or not that makes sense in the context of what you're doing, I have no idea...

For that matter, you could just 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 are type1 and type2 representing?

Upvotes: 3

Related Questions