与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