文章

Python入门小记(3):函数,类

最后需要了解的入门知识,函数和类

函数

函数的定义以及调用方式

1.可以通过示例的函数和相关调用看出Python中函数的一些特征,比较特别的地方有

  1. 使用def关键字来表示将要开始定义一个函数
  2. 从函数内容开始的行,到函数的结束行,缩进的字符数都必须大于0,且以函数内容的第一行的缩进数为基准,按照Python的缩进规则进行代码编写,到不进行缩进的行为止,则不为该函数的内容
1
2
3
4
5
6
7
8
9
10
11
12
13
def printUserID(userName, userID=1):  # 冒号表示函数开始
    print(userName + "'s userID is " + str(userID))
    return 'OK'


printUserID('Tony', 2)
printUserID(userName='John', userID=3)
print(printUserID('Jack'))
# 输出内容
# Tony's userID is 2
# John's userID is 3
# Jack's userID is 1
# OK

传递任意数量的实参

1.用星号可以让多个参数作为一个元组传进函数中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def printNumers(tilte, *numbers):
    for number in numbers:
        print(tilte + str(number))


title = "This is "
printNumers(title)
printNumers(title, 0)
printNumers(title, 1, 2, 3)
# 输出内容
# This is 0
# This is 1
# This is 2
# This is 3

使用任意数量的关键字实参

1.用两个星号让参数以字典的形式传进函数中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def printSetting(userName, **settings):
    print(userName + ' setting:')
    for key, value in settings.items():
        print("loading...")
    print(settings)


printSetting("Tom", Enable=True, Font='Big', Location='China')
# 输出内容
# Tom setting:
# loading...
# loading...
# loading...
# {'Enable': True, 'Font': 'Big', 'Location': 'China'}

使用模块中的函数

首先,我们新建几个文件,表示不同的模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# animal_one.py
def print_animal_one():
    print('An animal')

# animal_two.py
def print_animal_two():
    print('Two animals')

# animal_three.py
def print_animal_three():
    print('Three animals')


def print_animal_two():
    print('Two animals in three')

接着,在一个模块中进行导入和函数调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# call_animals.py
import animal_one  # 导入整个模块,在调用具体函数时使用模块名加句点的方式
from animal_two import print_animal_two  # 导入指定模块中的指定函数
import animal_one as t  # 使用as给模块指定别名
from animal_two import print_animal_two as print_two  # 使用as给函数指定别名
from animal_three import *  # 引入指定模块中的所有函数,在调用时不需要使用句点

animal_one.print_animal_one()
print_animal_two()
t.print_animal_one()
print_two()
print_animal_three()
# An animal
# Two animals in three
# An animal
# Two animals
# Three animals

1.从上面的示例中不难看出在Python中如何使用模块中的函数,值得注意的是,如果进行了重复导入,行号靠后的导入会覆盖之前的导入

定义类

首先,我们新建一个文件,创建两个类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# animals.py
class Dog():

    def sit(self):
        print('小狗蹲下了')

    def roll(self):
        print('小狗打了个滚')


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

    def meow(self):
        print('喵~')

    def run(self):
        print(self.name + '跑起来了')

1.类中的函数被称为方法,__init__()是一个特殊的方法,每次创建新实例时,都会自动调用它,开头和末尾的下划线是一种约定,为了避免Python默认方法与普通方法发生冲突,在这个方法中,可以进行对属性进行定义并初始化等操作

2.方法的定义中都必须包含形参self,它是一个指向实例本身的引用,让实例能访问类中的属性和方法,在调用方法时,此参数会自动传递

导入并使用类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# call_animals.py
from animals import Dog, Cat

myDog = Dog()
myDog.sit()
myDog.roll()
myCat = Cat("Cola")
myCat.name = "可乐"
myCat.meow()
myCat.run()
# 输出内容
# 小狗蹲下了
# 小狗打了个滚
# 喵~
# 可乐跑起来了

继承

在已有animals模块的基础上创建新的类并对其进行调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# AmazingCat.py
from animals import Cat


class AmazingCat(Cat):
    def __init__(self, name, size):
        super().__init__(name)  # 初始化父类的属性
        self.size = size  # 初始化LittleCat类的特有属性

    def meow(self):
        print('meow~')

    def description(self):
        print(self.name + " is a " + self.size + " cat")


myLittleCat = AmazingCat("Cola", "little")
myLittleCat.meow()
myLittleCat.run()
myLittleCat.description()
# 输出内容
# meow~
# Cola跑起来了
# Cola is a little cat

1.首先需要注意的是,在子类AmazingCat的首行,定义子类时,在括号内指定父类的名称,第一个__init__指定AmazingCat需要的所有参数

2.通过使用特殊函数super(),让父类和子类相关联,这里调用父类的__init__方法对父类的内容进行初始化,从而让子类也包含父类的所有属性。因为父类也被成为超类(superclass),所以这个函数名为super

3.需要重写父类的方法,只需要在子类定义父类中同名的方法

P.S.

在Python中,存在一些内置的标准库,可以在实际使用中用import直接调用,这里演示标准库中的一个类OrderedDict,其与字典几乎完全相同,区别只在于记录了键值对的添加顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
from collections import OrderedDict

dict_ordered = OrderedDict()
dict_ordered['Tony'] = 'Los Angeles'
dict_ordered['Jack'] = 'San Francisco'
dict_ordered['Tom'] = 'California'

for name, hometown in dict_ordered.items():
    print(name + " is from " + hometown)
# 输出结果
# Tony is from Los Angeles
# Jack is from San Francisco
# Tom is from California
本文由作者按照 CC BY 4.0 进行授权