python自定义模块属性错误_name _

发布于 2025-01-19 17:06:35 字数 841 浏览 4 评论 0原文

我观察到 python 的一个非常奇怪的行为:对于任何属性或函数的任何自定义模块,我都会收到属性错误,尽管 dir() 告诉我它存在。

我做什么:

我有一个名为 testmodule.py 的模块:

def printing(text):
   print("something and "+text)

在我的 main 中我做了:


import testmodule as tm

print(dir(tm))
print(tm._name_)

我得到什么:

dir() 的输出看起来如预期:['__builtins__'、'__cached__'、'__doc__'、'__file__'、'__loader__'、'__name__'、'__package__'、'__spec__'、'打印']

但后来我得到:AttributeError:模块'testsite_function'没有属性'_file_'。无论我调用哪个属性或函数,都会发生这种情况。

更多: 我不知道这是否是有用的信息: 我使用 python 3.8.10 解释器。 我在虚拟环境中工作。它已激活并且到目前为止没有造成任何问题。 main 和 testmodule.py 都位于同一文件夹中。 我正在通过 ssh 远程使用 VS Code。到目前为止,这没有造成任何问题。 前几天还没有出现这样的问题。我同时重新安装了vscode,版本和之前一样。 直接在终端执行main也会出现同样的问题。 其他模块如 numpy 工作。

I observe a very strange behavior with python: I get an attribute error for any custom module for any attribute or function, although dir() tells me it exists.

What I do:

I have a module called testmodule.py:

def printing(text):
   print("something and "+text)

In my main I do:


import testmodule as tm

print(dir(tm))
print(tm._name_)

What I get:

The output of dir() looks as expected: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'printing']

But then I get: AttributeError: module 'testsite_function' has no attribute '_file_'. This happens no matter which attribute or function I call.

More:
I do not know whether this is useful information:
I use an python 3.8.10 interpreter.
I am working in an virtual enviroment. It is activated and has caused no problems so far.
Both, main and testmodule.py are in the same folder.
I am working with vs code in remote via ssh. This caused no problems so far.
A few days ago there were no such problems. I reinstalled vscode in the meantime, with the same version as before.
The same problem occures when executing main on the terminal directly.
Other modules like numpy work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2025-01-26 17:06:35

您需要使用双下划线:

print(tm.__name__)

You need to use double underscores:

print(tm.__name__)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文