【发布时间】:2019-08-06 04:58:14
【问题描述】:
我在 python 中有一个相当大的项目,所以我将我的自定义类分解为它们自己的 .py 文件。其中许多类使用其他自定义类作为输入参数。当我使用From custom_file Import CustomClass 导入自定义类时,VS Code 的(我认为 IntelliSense 功能)无法像全局导入(numpy、matplotlib 等)那样识别本地导入类的属性和方法。
为具有许多自定义类的项目设置文件结构的最佳方法是什么?我是否应该将类分离到它们自己的文件中,将自定义类作为其他自定义类的输入是标准的,是否有正确的方法来跟踪自定义类的所有可用方法和属性? (不断翻阅文件以确保我正确输入了属性名称很麻烦)。
示例文件结构:
-Main.py(从 Bolt 导入 Bolt) - bolt.py 是一个包含 Bolt 类的文件,它需要 (length: double, thread: Thread)。螺栓从螺纹中导入螺纹 -thread.py 是一个包含 Thread 的文件,它需要(直径:double,pitch:int,class:int)
在我的 Main.py 中,我有另一个使用 Bolt 作为输入的类,在该类中,我想获取线程类。为此,我使用self.bolt.thread.class,,但IntelliSense 建议在输入self.bolt. 后注明
也许从更高的层次来看,习惯上是让类作为输入提供给其他类,而不是像继承这样的事情(我对此了解不多)。 对于上面的例子,我做事的方式是:(如果这不是正确的做事方式,请告诉我)
# File 1 --- thread.py
class Thread:
def __init__(self, diameter: double, pitch: int, cls: int):
self.diameter = diameter
self.pitch = pitch
self.cls = cls
# File 2 --- bolt.py
from thread import Thread
class Bolt:
def __init__(self, length: double, thrd: Thread):
self.length = length
self.thrd = thrd
# File 3 --- joint.py
from bolt import Bolt
class Joint:
def __init__(self, num_bolts: int, bolt: Bolt):
self.num_bolts = num_bolts
self.bolt = bolt
def get_thrd_class(self):
return self.bolt.thrd.cls
# File 4 --- main.py
from joint import Joint
from bolt import Bolt
from thread import Thread
thrd = Thread(.25, 20, 3)
bolt = Bolt(1.25, thrd)
joint = Joint(5, bolt)
cls = joint.get_thread_class()
【问题讨论】:
-
这对我来说看起来不错。
thread.py、bolt.py、joint.py和main.py是否都在同一个目录中? -
是的,它们都在同一个目录中
标签: python class import visual-studio-code