[英]When importing a file that has classes, do class attributes get initialized?
I'm a beginner in python, so please bear with me.我是python的初学者,请多多包涵。 I read somewhere that when you import a file, it's exactly as if you executed that file.我在某处读到,当你导入一个文件时,就好像你执行了那个文件一样。 This confused me because I started wondering whether class attributes also get initialized when importing.这让我感到困惑,因为我开始怀疑 class 属性在导入时是否也被初始化。
Let me give you an example,让我举一个例子,
Say we have this file named cat.py:假设我们有这个名为 cat.py 的文件:
#cat.py
class RawFeature:
bat = 5
And we have another file here:我们这里还有另一个文件:
import cat as c
#Does 'bat' get initialized upon calling?
print(c.RawFeature.bat)
Does 'bat' get initialized upon calling or when the 'cat.py' file is imported? “bat”是否在调用时或导入“cat.py”文件时被初始化?
If it gets initialized upon importing this really changes the flow of the script because let's say the class variable 'bat' is initialized by calling some function...如果它在导入时被初始化,这真的会改变脚本的流程,因为假设 class 变量“bat”是通过调用一些 function 来初始化的......
RawFeature.bat
will be initialized as soon as you import the module cat
or anything from the module like RawFeature
. RawFeature.bat
将在您导入模块cat
或模块中的任何内容(如RawFeature
。 As a quick litmus test, if you store the following in a file called thing.py
,作为快速试金石,如果将以下内容存储在名为thing.py
的文件中,
def initialize():
print('Calling initialize')
return 5
class Thing:
class_attr = initialize()
then try to import thing
or Thing
in a Python REPL shell, you'll noticed that Calling initialize
gets printed before making any further calls.然后尝试在 Python REPL shell 中导入thing
或Thing
,您会注意到在进行任何进一步调用之前会打印Calling initialize
。
@rajith-thennakoon - @rajith-thennakoon-
Adding to kingkupps reponse, If you want your class/methods/anyCodeSnippet to restrict from getting initialized while being imported, you can add the class/methods/anyCodeSnippet in the if block as mentioned below.添加到 kingkupps 响应,如果您希望您的类/方法/anyCodeSnippet 在导入时限制被初始化,您可以在 if 块中添加类/方法/anyCodeSnippet,如下所述。
if __name__ == "__main__":
def initialize():
print('Calling initialize')
return 5
class Thing:
class_attr = initialize()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.