简体   繁体   English

python将变量添加到导入的模块

[英]python adding variables to imported modules

I wasn't looking what I had previously written on the line so I accidently declared a variable in ipython as: 我没有看我以前在网上写的内容,所以我不小心在ipython中将变量声明为:

np.zerosn=10

Surprisingly this was allowed. 令人惊讶的是,这是允许的。 So I thought that maybe it was because you can name use periods in your variable names, but that is not the case. 因此,我认为可能是因为您可以在变量名中命名使用句点,但事实并非如此。 So I'm wondering what is actually happening. 所以我想知道实际发生了什么。 Is this adding a new variable to the numpy module? 这是否将新变量添加到numpy模块?

Yes. 是。

In general, (most/many) python objects have dynamic attribute spaces, and you can stick whatever you want onto them whenever you want. 通常,(大多数)Python对象具有动态属性空间,您可以随时将所需的内容粘贴到它们上。 And modules are just objects. 模块只是对象。 Their attribute space is essentially the same as their global scope. 它们的属性空间与全局范围基本相同。

Pure python functions are another (perhaps surprising) example of something onto which you can stick arbitrary attributes, though these are not associated with the function's local scope. 纯python函数是另一个示例(可能令人惊讶),可以在其中粘贴任意属性,尽管这些属性与函数的本地范围无关。

Most 'builtin' types (ie those which are implemented in extension modules, rather than those that are found in the __builtins__ module) and their instances, do not have dynamic attribute spaces. 大多数“内置”类型(即在扩展模块中实现的类型,而不是在__builtins__模块中找到的类型)及其实例都没有动态属性空间。 Neither do pure python types with __slots__ . 带有__slots__纯python类型也没有。

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

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