gpt4 book ai didi

python - 从相同文件与不同文件与 __init__.py 实例化 python 类

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:14 25 4
gpt4 key购买 nike

我是Python新手,Q1 :我想知道,为什么 print 语句执行多次,即使我只调用了一次 school1.print_name() ?

Q2:创建新对象时创建的__init__.py的目的是什么 包?

Q3:从 otherfile.py 创建对象与 __init__.py

(注意:我调试了 otherfile.py 和 init.py 中的代码,其中脚本在调用 school1.print_name() 后并未终止,而是从开始处再次运行脚本)

SameFile.py

class School:

def __init__(self, name):
self.name = name

def print_name(self):
print("School name is : " + self.name)

school1 = School("DPS") # 1
school1.print_name()` # 2
# These 1 and 2 lines are removed from this file when running from otherfile.py and __init__.py

o/p:

School name is : DPS

OtherFile.py

import School

school1 = School("DPS")
school1.print_name()

o/p:

School name is : DPS
School name is : DPS #why did it print second time

__init__.py

import School

school1 = School("DPS")
school1.print_name()

o/p:

School name is : DPS
School name is : DPS #why did it print second time

最佳答案

考虑以下文件结构:

mymodule/
__init__.py
Buildings.py

让我们暂时将__init__.py 保留为空。 Buildings.py 如下所示:

class School:

def __init__(self, name):
self.name = name

def print_name(self):
print("School name is : " + self.name)


if __name__ == '__main__':
school1 = School("DPS -- Buildings.py")
school1.print_name()

在文件 test.py 中使用您的模块,如下所示:

from mymodule.Buildings import School

school = School('DPS - test.py')
school.print_name()

这将正确打印 DPS - test.py,正如我们所期望的那样。由于 __init__.py 为空,因此不会打印任何其他内容。然而,如果我们将任何打印语句放入 __init__.py 中,则在从 mymodule 模块导入任何内容时都会显示该语句。

更改__init__.py:

from mymodule.Buildings import School 

print('__init__.py is loaded!')

school = School('DPS - __init__.py')
school.print_name()

并运行test.py,这将产生以下输出:

__init__.py is loaded!
School name is : DPS - __init__.py
School name is : DPS - test.py

所以你可以看到,加载模块时首先执行__init__.py,然后执行test.py中的其他行。

关于python - 从相同文件与不同文件与 __init__.py 实例化 python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58561386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com