初始化namesp模块中的类

2024-06-02 07:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个模块car.py。你知道吗

有引擎和轮胎,我希望它们(它们的方法和属性)可以作为

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

所以文件parts.py看起来像

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()

现在,在import car之后,我可以随意访问它们-car.engine.data

做这件事对吗?你知道吗


Tags: 模块py引擎selfdataobjectfooinit
1条回答
网友
1楼 · 发布于 2024-06-02 07:56:31

当然。。。我不太清楚你在问什么。。。你知道吗

你所做的没有错,但是你可以跳过初始化类。只要做:

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

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

不管你在做什么,我都不知道。。。你知道吗

就这点而言,你可以

class Container(object):
    pass

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

或者其他类似的事情。。。type1type2代表什么?你知道吗

相关问题 更多 >