Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing classes in module for namespace

Tags:

python

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?

like image 472
Qiao Avatar asked Apr 02 '26 17:04

Qiao


1 Answers

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?

like image 181
Joe Kington Avatar answered Apr 04 '26 06:04

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!