【Python】__init__.py和__init__函数的作用和用法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值