简体   繁体   English

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

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

I'm kinda new to Python, so i'm still lost in the whole namespace thing. 我是Python的新手,所以我仍然迷失在整个命名空间中。 I've created a package, with the init file in it and also a classname.py file, with the class, obviously. 我已经创建了一个包,其中包含init文件,还有一个带有类的classname.py文件。 For instance: from parachute import container, emitter 例如:从降落伞进口容器,发射器

I tried to instance the class Container directly, but it gave me an error, so i had to instance it as container.Container(). 我试图直接实例化类Container,但是它给了我一个错误,因此我不得不将其实例化为container.Container()。 How can i avoid doing this? 我如何避免这样做? Basically, what i want to do is to import a class from a package and avoid typing the package name and/or the file name. 基本上,我想做的是从包中导入一个类,并避免键入包名和/或文件名。 Thanks in advance, and please let me know if the question isn't clear enough. 预先谢谢您,如果问题不够清楚,请告诉我。

UPDATE The structure i have is: - parachute -- init .py 更新的结构,我有是: -降落伞- 初始化的.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.

Now, from outside the package i'm calling Container and passing some arguments, and the Container instances and distributes the arguments as it needs. 现在,我从程序包外部调用Container并传递一些参数,然后Container实例将根据需要分配参数。 I have the impression that this isn't the best way to do what i need to do, which is: Create a collection of sparkles, owned by the emitter. 我的印象是,这并不是做我需要做的最好的方法,这是:创建由发射器拥有的火花集合。

from module import Class
classInst = Class()

This will work if your class is in module.py 如果您的课程在module.py中,则可以使用

Don't put the class in it's own file. 不要将类放在自己的文件中。 Put Container and Emitter directly in parachute.py . ContainerEmitter直接放在parachute.py

You can then do 然后你可以做

from parachute import Container, Emitter

or 要么

import parachute

container = parachute.Container()

This essentially boils down to "Python isn't Java so for best results, don't treat it like it is" ;) 这本质上可以归结为“ Python不是Java,所以为了获得最佳结果,请不要像对待它一样对待它;”)

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

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