1. __init__.py的作用和用法
- 在一个包含多个函数的目录下使用__init__.py
- 它可以把这些函数打包成一个package
- 好处:在其他程序中调用函数的时候不需要很多个详细的import,只需要import这些函数所在的目录即可
- __init__.py中的内容
import name_of_dir.name_of_py_file
ii. short_name = name_of_dir.name_of_py_file.name_of_function
import arithmetic.add
add = arithmetic.add.add
- 在main.py中调用
import arthmetic as a4
result = a4.add(x, y)
2. __init__函数的作用
在类中定义__init__函数用来方便对类的属性进行定义,而不用另外命名一个函数完成属性定义工作。因为下划线开头的函数表示私有函数不能被类的外部调用,所以不需要调用类的属性函数这一步
class Box:
#def setDimension(self, width, height, depth):
# self.width = width
# self.height = height
# self.depth = depth
def __init__(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth
参考:
[1] https://blog.csdn.net/luzhan66/article/details/82822896