簡體   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