繁体   English   中英

当实例化从包中导入的“类”时,如何避免使用package.class()声明?

[英]When instancing an imported “class” from a package, how can i avoid using the package.class() declaration?

我是Python的新手,所以我仍然迷失在整个命名空间中。 我已经创建了一个包,其中包含init文件,还有一个带有类的classname.py文件。 例如:从降落伞进口容器,发射器

我试图直接实例化类Container,但是它给了我一个错误,因此我不得不将其实例化为container.Container()。 我如何避免这样做? 基本上,我想做的是从包中导入一个类,并避免键入包名和/或文件名。 预先谢谢您,如果问题不够清楚,请告诉我。

更新的结构,我有是: -降落伞- 初始化的.py

-- container.py
    Serves as a controller, i'd say, instancing, calling and glueing all the other parts    together.

-- sparkles.py
    Has two classes: Sparkle and Sparkles. Sparkle is a single element, with only one    property so far, and Sparkles serves as a collection.  Sparkles() belongs to the Emitter, and Sparkle() belongs to Sparkles().

-- emitter.py 
    Emitter could be seen as the user entity. It has a name and an uid, it belongs to a Container and the Container belongs to it.

现在,我从程序包外部调用Container并传递一些参数,然后Container实例将根据需要分配参数。 我的印象是,这并不是做我需要做的最好的方法,这是:创建由发射器拥有的火花集合。

from module import Class
classInst = Class()

如果您的课程在module.py中,则可以使用

不要将类放在自己的文件中。 ContainerEmitter直接放在parachute.py

然后你可以做

from parachute import Container, Emitter

要么

import parachute

container = parachute.Container()

这本质上可以归结为“ Python不是Java,所以为了获得最佳结果,请不要像对待它一样对待它;”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM