python之类别以及模组

与Java 相比,Python 的类别不支援interface 和protected 修饰词,但允许多重继承。

# 无继承
class Math:
    def __init__(self):
        pass

# 继承单一类别
class Math(object):
    def __init__(self):
        pass

# 继承多个类别
class Math(object, object2):
    def __init__(self):
        pass

Python 类别的基本结构如下:

# Math 类别继承 object
class Math(object):
    # 静态变数
    PI = 3.14

    # 建构函数
    def __init__(self):
        super().__init__()      # 呼叫父类别建构函数
        self.a = 1              # 实例变数 (公开)
        self.__b = 2            # 实例变数 (私有)
        self.func1()            # 呼叫类别函数

    # 实例函数 (公开)
    def func1(self):
        pass

    # 实例函数 (私有)
    def __func2(self):
        pass

    # 静态函数
    @staticmethod
    def func3():
        pass

# 使用类别
math = Math()
math.func1()

模组结构进行说明

# 目录结构
# package
# |_ module_1.py
# |_ class_1.py
# test.py

# module.py 内容
def test1():
    print('module_1 > test1()')

def test2():
    print('module_1 > test2()')


# class_1.py 内容
class Class1:
    def __init__(self):
        pass

    def info(self):
        print('Class1.info()')

在test.py 程式中使用模块。

 
# 引入函数
# 引入全部函数 from package.module_1 import *
# 引入单一函数 from package.module_1 import test1
from package.module_1 import *
test1()
test2()

# 引入类别
from package.class_1 import Class1
class_test = Class1()
class_test.info()

使用__init__.py 档

__init__.py 档,是用来宣告这个资料夹为一个模组,档案可以完全没有内容,但也可以用来简化import 语句。 在package 目录中加入__init__.py 档,并填入以下内容。

# 在 __init__.py 写入以下内容
from package.module_1 import test1
from package.module_1 import test2
from package.class_1 import Class1

# 在 test.py 程式中使用模块
from package import *
test1()
test2()
class_test = Class1()
class_test.info()

单一叙述多行撰写

有时候可能一行程式码非常的长,我们可以使用斜线(\) 多行撰写。

# 原程式码
x = a + b + c + d + e

# 多行撰写程式码
x = a \
    + b \
    + c \
    + d \
    + e

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值