有开发经验 ,初学Python基础篇


原文地址: Learn Python in y minutes

本篇教程专为有开发经验的Python初学者使用,它能让你在几分钟之内上手,对Python有一个大概的了解。

注意:本文适用于Python 3。

一、原始数据类型和操作符

# 单行注释以数字符号开头。

""" 多行字符串可以使用
	三个 ‘ " ’ 来编写,通常用作文档。
"""

####################################################
## 1. Primitive Datatypes and Operators
####################################################

# You have numbers
3  # => 3

# Math is what you would expect
1 + 1   # => 2
8 - 1   # => 7
10 * 2  # => 20
35 / 5  # => 7.0

# 整数除法对正数和负数都取整。
5 // 3       # => 1
-5 // 3      # => -2
5.0 // 3.0   # => 1.0 # 也适用于浮点数 floats
-5.0 // 3.0  # => -2.0

# 除法的结果总是一个浮点数
10.0 / 3  # => 3.3333333333333335

# 模操作
7 % 3  # => 1

# 求幂(x* y, x ^ y)
2**3  # => 8

# 使用括号强制优先级
(1 + 3) * 2  # => 8

# 布尔值是基本类型(注意:大写)
True
False

# 否定与不
not True   # => False
not False  # => True

# 布尔操作符
# 注意“and”和“or”是区分大小写的
True and False  # => False
False or True   # => True

# True和False实际上是1和0,但是它们的关键字不同
True + True # => 2
True * 8    # => 8
False - 5   # => -5

# 比较运算符查看真和假的数值
0 == False  # => True
1 == True   # => True
2 == True   # => False
-5 != False # => True

# 在ints上使用布尔逻辑运算符将它们转换为布尔值进行计算,但是返回它们的非转换值
#不要把bool(int)和bitwise and/or(&,|)混在一起
bool(0)     # => False
bool(4)     # => True
bool(-6)    # => True
0 and 2     # => 0
-5 or 0     # => -5

# 等于是 ==
1 == 1  # => True
2 == 1  # => False

# 不等于是 !=
1 != 1  # => False
2 != 1  # => True

# 更多的比较
1 < 10  # => True
1 > 10  # => False
2 <= 2  # => True
2 >= 2  # => True

# 查看一个值是否在范围内
1 < 2 and 2 < 3  # => True
2 < 3 and 3 < 2  # => False
# 也可以连起来比对
1 < 2 < 3  # => True
2 < 3 < 2  # => False

# (is vs. ==) 是检查两个变量是否引用同一个对象,but == checks
# 如果指向的对象具有相同的值。
a = [1, 2, 3, 4]  # Point a at a new list, [1, 2, 3, 4]
b = a             # Point b at what a is pointing to
b is a            # => True, a and b refer to the same object
b == a            # => True, a's and b's objects are equal
b = [1, 2, 3, 4]  # Point b at a new list, [1, 2, 3, 4]
b is a            # => False, a and b do not refer to the same object
b == a            # => True, a's and b's objects are equal

# 字符串是用 " 或者 ' 来创建的
"This is a string."
'This is also a string.'

# 字符串也可以用 + 连接!但是尽量不要这样做。
"Hello " + "world!"  # => "Hello world!"
# 可以不使用'+'连接字符串文字(但不是变量)
"Hello " "world!"    # => "Hello world!"

# 可以将字符串视为字符列表
"This is a string"[0]  # => 'T'

# 你可以求出一个字符串的长度
len("This is a string")  # => 16

# .format 可以用来格式化字符串,像这样:
"{} can be {}".format("Strings", "interpolated")  # => "Strings can be interpolated"

# 您可以重复格式化参数以节省一些输入。
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"

# 你可以使用关键字,如果你不想计数。
"{name} wants to eat {food}".format(name="Bob", food="lasagna")  # => "Bob wants to eat lasagna"

# 如果您的Python 3代码也需要运行在Python 2.5及以下,您也可以
# 仍然使用旧的格式:
"%s can be %s the %s way" % ("Strings", "interpolated", "old")  # => "Strings can be interpolated the old way"

# 还可以使用f-string或格式化的字符串文字进行格式化(在Python 3.6+中)
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
# 你基本上可以把任何Python语句放在大括号里,它就会被输出到字符串里。
f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."


# None是一个对象
None  # => None

# 不要使用“==”符号将对象与None进行比较
# 用“是”代替。这将检查对象标识是否相等。
"etc" is None  # => False
None is None   # => True

# None、0和空字符串/列表/dicts/元组的值都为False。
# 其他值都为真
bool(0)   # => False
bool("")  # => False
bool([])  # => False
bool({})  # => False
bool(())  # => False

二、变量和集合

####################################################
## 2. Variables and Collections
####################################################

# Python有一个打印函数
print("I'm Python. Nice to meet you!")  # => I'm Python. Nice to meet you!

# 默认情况下,print函数也会在末尾打印出一个换行符。
# 使用可选参数end来更改结束字符串。
print("Hello, World", end="!")  # => Hello, World!

# 从控制台获取输入数据的简单方法
input_string_var = input("Enter some data: ") # 以字符串的形式返回数据
# 注意:在Python的早期版本中,input()方法被命名为raw_input()

# 没有声明,只有赋值。
# 惯例是使用lower_case_with_下划线
some_var = 5
some_var  # => 5

# 访问以前未分配的变量是一个异常。
# 有关异常处理的更多信息,请参见控制流。
some_unknown_var  # Raises a NameError

# if 可以用作一种表达方式
# 相当于 C's '?:' 三元运算符	Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2  # => "yahoo!"

# 列表存储序列
li = []
# 您可以从一个预填充的列表开始
other_li = [4, 5, 6]

# 使用append将内容添加到列表的末尾
li.append(1)    # li is now [1]
li.append(2)    # li is now [1, 2]
li.append(4)    # li is now [1, 2, 4]
li.append(3)    # li is now [1, 2, 4, 3]
# 从最后用pop移除
li.pop()        # => 3 and li is now [1, 2, 4]
# 我们把它放回去
li.append(3)    # li is now [1, 2, 4, 3] again.

# 像访问任何数组一样访问列表
li[0]   # => 1
# 看看最后一个元素
li[-1]  # => 3

# 看一下索引出界时的错误
li[4]  # Raises an IndexError

# 您可以使用切片语法查看范围。
# 包括开始索引,不包括结束索引
# (这是一个封闭/开放的范围为您的数学类型。)
li[1:3]   # Return list from index 1 to 3 => [2, 4]
li[2:]    # Return list starting from index 2 => [4, 3]
li[:3]    # Return list from beginning until index 3  => [1, 2, 4]
li[::2]   # Return list selecting every second entry => [1, 4]
li[::-1]  # Return list in reverse order => [3, 4, 2, 1]
# 使用它们的任意组合来制作高级切片
# li[start:end:step]

# 使用切片制作一层深度复制
li2 = li[:]  # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.

# 用“del”从列表中删除任意元素
del li[2]  # li is now [1, 2, 3]

# 删除第一个出现的值
li.remove(2)  # li is now [1, 3]
li.remove(2)  # Raises a ValueError as 2 is not in the list

# 在特定索引处插入一个元素
li.insert(1, 2)  # li is now [1, 2, 3] again

# 获取与参数匹配的第一项的索引
li.index(2)  # => 1
li.index(4)  # Raises a ValueError as 4 is not in the list

# 你可以添加列表
# 注意:li和other_li的值没有修改。
li + other_li  # => [1, 2, 3, 4, 5, 6]

# 使用“extend()”连接列表
li.extend(other_li)  # Now li is [1, 2, 3, 4, 5, 6]

# 用“in”检查列表是否存在
1 in li  # => True

# 使用“len()”检查长度
len(li)  # => 6


# 元组类似于列表,但是是不可变的。
tup = (1, 2, 3)
tup[0]      # => 1
tup[0] = 3  # Raises a TypeError

# 注意,长度为1的元组必须在最后一个元素but后面有逗号
# 其他长度的元组,即使是0,也不需要。
type((1))   # => <class 'int'>
type((1,))  # => <class 'tuple'>
type(())    # => <class 'tuple'>

# 您也可以对元组执行大多数列表操作
len(tup)         # => 3
tup + (4, 5, 6)  # => (1, 2, 3, 4, 5, 6)
tup[:2]          # => (1, 2)
2 in tup         # => True

# 您可以将元组(或列表)解压缩到变量中
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3
# 你也可以延长开箱时间
a, *b, c = (1, 2, 3, 4)  # a is now 1, b is now [2, 3] and c is now 4
# 如果省略括号,则默认创建元组
d, e, f = 4, 5, 6  # tuple 4, 5, 6 is unpacked into variables d, e and f
# 分别为, d = 4, e = 5 and f = 6
# 现在看看交换两个值是多么容易
e, d = d, e  # d is now 5 and e is now 4


# 字典存储从键到值的映射
empty_dict = {}
# 这是一本预先填好的字典
filled_dict = {"one": 1, "two": 2, "three": 3}

# 字典的键必须是不可变类型。这是为了确保
# 可以将键转换为常量散列值,以便快速查找。
# 不可变类型包括int、float、string、tuple。
invalid_dict = {[1,2,3]: "123"}  # => Raises a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]}   # Values can be of any type, however.

# 使用[]查找值
filled_dict["one"]  # => 1

# 使用“keys()”将所有键作为可迭代的。我们需要将调用封装在list()中
# 把它变成一个列表。这些我们稍后再谈。注-适用于Python
# 版本<3.7,字典键顺序不保证。你的结果可能
# 与下面的示例不完全匹配。然而,从Python 3.7开始,字典
# 项保持它们被插入字典的顺序。
list(filled_dict.keys())  # => ["three", "two", "one"] in Python <3.7
list(filled_dict.keys())  # => ["one", "two", "three"] in Python 3.7+


# 使用“values()”将所有值作为可迭代的。我们需要再一次把它包起来
# 在list()中将它从iterable中取出。注:与上述键排序相同。
list(filled_dict.values())  # => [3, 2, 1]  in Python <3.7
list(filled_dict.values())  # => [1, 2, 3] in Python 3.7+

# 使用“in”检查字典中的键是否存在
"one" in filled_dict  # => True
1 in filled_dict      # => False

# 查找不存在的密钥是一个密钥错误
filled_dict["four"]  # KeyError

# 使用“get()”方法来避免密钥错误
filled_dict.get("one")      # => 1
filled_dict.get("four")     # => None
# get方法在值丢失时支持默认参数
filled_dict.get("one", 4)   # => 1
filled_dict.get("four", 4)  # => 4

# “setdefault()”仅在给定键不存在时才插入字典
filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5

# 添加到字典中
filled_dict.update({"four":4})  # => {"one": 1, "two": 2, "three": 3, "four": 4}
filled_dict["four"] = 4         # another way to add to dict

# 使用del从字典中删除键
del filled_dict["one"]  # Removes the key "one" from filled dict

# 在Python 3.5中,您还可以使用附加的解包选项
{'a': 1, **{'b': 2}}  # => {'a': 1, 'b': 2}
{'a': 1, **{'a': 2}}  # => {'a': 2}



# Sets store ... well sets
empty_set = set()
# 用一组值初始化一个集合。它看起来有点像字典,抱歉。
some_set = {1, 1, 2, 2, 3, 4}  # some_set is now {1, 2, 3, 4}

# 与字典的键类似,集合的元素必须是不可变的。
invalid_set = {[1], 1}  # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}

# 向集合中再添加一项
filled_set = some_set
filled_set.add(5)  # filled_set is now {1, 2, 3, 4, 5}
# 集合没有重复的元素
filled_set.add(5)  # it remains as before {1, 2, 3, 4, 5}

# 设置交集用 &
other_set = {3, 4, 5, 6}
filled_set & other_set  # => {3, 4, 5}

# 设置并集用 |
filled_set | other_set  # => {1, 2, 3, 4, 5, 6}

# 设置差异用 -
{1, 2, 3, 4} - {2, 3, 5}  # => {1, 4}

# 设置对称差分用 ^
{1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}

# 检查左边的集合是否是右边集合的超集
{1, 2} >= {1, 2, 3} # => False

# 检查左边的集合是否是右边集合的子集
{1, 2} <= {1, 2, 3} # => True

# 用in检查集合是否存在元素
2 in filled_set   # => True
10 in filled_set  # => False

三、控制流和迭代

####################################################
## 3. Control Flow and Iterables
####################################################

# 让我们来定义一个变量
some_var = 5

# 这是一个if语句。缩进在Python中非常重要!
# 惯例是使用四个空格,而不是制表符。
# 输出"some_var is smaller than 10."
if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # 这个elif子句是可选的。
    print("some_var is smaller than 10.")
else:                  # 这也是可选的。
    print("some_var is indeed 10.")


"""
For循环遍历列表
打印:
    狗是哺乳动物
	猫是哺乳动物
	老鼠是哺乳动物
"""
for animal in ["dog", "cat", "mouse"]:
    # 可以使用format()插入格式化的字符串
    print("{} is a mammal".format(animal))

"""
“range(number)”返回一个可迭代的数字
从0到给定数字
打印:
    0
    1
    2
    3
"""
for i in range(4):
    print(i)

"""
“range((lower, upper)”返回一个可迭代的数字
从下数到上数
打印:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print(i)

"""
"range(lower, upper, step)" 返回一个可迭代的数字
从较低的数到较高的数,同时递增
的一步。如果未指定步骤,则默认值为1。
打印:
    4
    6
"""
for i in range(4, 8, 2):
    print(i)

"""
循环遍历列表,并检索列表中每个项的索引和值
打印:
    0 dog
    1 cat
    2 mouse
"""
list = ["dog", "cat", "mouse"]
for i, value in enumerate(list):
    print(i, value)

"""
While循环执行,直到不再满足条件为止。
打印:
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print(x)
    x += 1  # x = x + 1的简写

# 使用try/except块处理异常
try:
    # 使用“raise”来引发错误
    raise IndexError("This is an index error")
except IndexError as e:
    pass                 # 通行证是无效的。通常你会在这里做恢复。
except (TypeError, NameError):
    pass                 # 如果需要,可以一起处理多个异常。
else:                    # try/except块的可选子句。必须遵循所有除了块
    print("All good!")   # 只有在try中的代码没有引发异常时才运行
finally:                 # 在任何情况下执行
    print("We can clean up resources here")

# 您可以使用with语句来代替try/finally来清理资源
with open("myfile.txt") as f:
    for line in f:
        print(line)

# Writing to a file
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
    file.write(str(contents))        # 将字符串写入文件

with open("myfile2.txt", "w+") as file:
    file.write(json.dumps(contents)) # 将对象写入文件

# Reading from a file
with open('myfile1.txt', "r+") as file:
    contents = file.read()           # 从文件中取出一个字符串
print(contents)
# print: {"aa": 12, "bb": 21}

with open('myfile2.txt', "r+") as file:
    contents = json.load(file)       # 从文件中读取json对象
print(contents)     
# print: {"aa": 12, "bb": 21}


# Python提供了一个称为Iterable的基本抽象。
# iterable是一个可以被当作序列的对象。
# range函数返回的对象是可迭代的。

filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)  # => dict_keys(['one', 'two', 'three']). 这是一个实现可迭代接口的对象。

# 我们可以对它进行循环。
for i in our_iterable:
    print(i)  # Prints one, two, three

# 但是,我们不能通过索引来处理元素。
our_iterable[1]  # Raises a TypeError

# iterable是知道如何创建迭代器的对象。
our_iterator = iter(our_iterable)

# 我们的迭代器是一个对象,当我们遍历它时,它可以记住状态。
# 我们用“next()”获得下一个对象。
next(our_iterator)  # => "one"

# 它在我们迭代时维护状态。
next(our_iterator)  # => "two"
next(our_iterator)  # => "three"

# 迭代器返回所有数据后,将引发StopIteration异常
next(our_iterator)  # Raises StopIteration

# 我们也可以对它进行循环,事实上,“for”隐含地完成了这个操作!
our_iterator = iter(our_iterable)
for i in our_iterator:
    print(i)  # Prints one, two, three

# 您可以通过调用list()获取iterable或iterator的所有元素。
list(our_iterable)  # => Returns ["one", "two", "three"]
list(our_iterator)  # => Returns [] because state is saved

四、Functions 功能方法

####################################################
## 4. Functions
####################################################

# 使用“def”创建新函数
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x + y  # 使用返回语句返回值

# 使用参数调用函数
add(5, 6)  # => prints out "x is 5 and y is 6" and returns 11

# 调用函数的另一种方法是使用关键字参数
add(y=6, x=5)  # 关键字参数可以以任何顺序到达。

# 你可以定义一个变量为的函数
# 位置参数
def varargs(*args):
    return args

varargs(1, 2, 3)  # => (1, 2, 3)

# 你可以定义一个变量为的函数
# 关键字参数也是如此
def keyword_args(**kwargs):
    return kwargs

# 让我们调用它看看会发生什么
keyword_args(big="foot", loch="ness")  # => {"big": "foot", "loch": "ness"}


# 如果你愿意,你可以同时做这两件事
def all_the_args(*args, **kwargs):
    print(args)
    print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
    (1, 2)
    {"a": 3, "b": 4}
"""

# 在调用函数时,您可以执行与args/kwargs相反的操作!
# 使用*来展开元组,使用**来展开kwarg。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)            # 等同于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs)         # 等同于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs)  # 等同于 all_the_args(1, 2, 3, 4, a=3, b=4)

# 返回多个值(带有tuple赋值)
def swap(x, y):
    return y, x  # 返回多个值作为一个没有圆括号的元组。
                 # (注:括号已被排除,但可以包括)

x = 1
y = 2
x, y = swap(x, y)     # => x = 2, y = 1
# (x, y) = swap(x,y)  # 括号也被排除,但可以包括在内。

# 功能范围
x = 5

def set_x(num):
    # 局部变量x与全局变量x不同
    x = num    # => 43
    print(x)   # => 43

def set_global_x(num):
    global x
    print(x)   # => 5
    x = num    # 全局变量x现在被设置为6
    print(x)   # => 6

set_x(43)
set_global_x(6)


# Python有第一类函数
def create_adder(x):
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)
add_10(3)   # => 13

# 还有匿名函数
(lambda x: x > 2)(3)                  # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1)  # => 5

# 有内置的高阶函数
list(map(add_10, [1, 2, 3]))          # => [11, 12, 13]
list(map(max, [1, 2, 3], [4, 2, 1]))  # => [4, 2, 3]

list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))  # => [6, 7]

# 我们可以对漂亮的映射和过滤器使用列表理解
# 列表理解将输出存储为列表,而列表本身可以是嵌套列表
[add_10(i) for i in [1, 2, 3]]         # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5]  # => [6, 7]

# 您也可以构建set和dict理解。
{x for x in 'abcddeef' if x not in 'abc'}  # => {'d', 'e', 'f'}
{x: x**2 for x in range(5)}  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

五、Modules 类

####################################################
## 5. Modules
####################################################

# 您可以导入模块
import math
print(math.sqrt(16))  # => 4.0

# 您可以从一个模块获得特定的函数
from math import ceil, floor
print(ceil(3.7))   # => 4.0
print(floor(3.7))  # => 3.0

# 您可以从一个模块导入所有函数。
# 警告:不建议这样做
from math import *

# 可以缩短模块名称
import math as m
math.sqrt(16) == m.sqrt(16)  # => True

# Python模块只是普通的Python文件。你
# 可以编写自己的,并导入它们。的名称
# 模块与文件的名称相同。

# 您可以找出模块中定义了哪些函数和属性。
import math
dir(math)

# 如果您有一个名为math.py的Python脚本
# 将math.py文件作为当前脚本
# 而不是内置的Python模块。
# 这是因为本地文件夹具有优先级
# 在Python的内置库之上。

六、Classes 模块

####################################################
## 6. Classes
####################################################

# 我们使用“class”语句来创建一个类
class Human:

    # 一个类的属性。它由这个类的所有实例共享
    species = "H. sapiens"

    # 基本初始化器,在实例化该类时调用。
    # 注意,双前导和双尾下划线表示对象
    # 或者是Python使用的属性,但是用户控制的属性
    # 名称空间。方法(或对象或属性)如下: __init__, __str__,
    # __repr__ etc. 被称为特殊方法(有时也称为dunder方法)
    # 你不应该自己编造这样的名字。
    def __init__(self, name):
        # 将参数赋给实例的name属性
        self.name = name

        # 初始化属性
        self._age = 0

    # 一个实例方法。所有方法都以“self”作为第一个参数
    def say(self, msg):
        print("{name}: {message}".format(name=self.name, message=msg))

    # 另一个实例方法
    def sing(self):
        return 'yo... yo... microphone check... one two... one two...'

    # 类方法在所有实例之间共享
    # 它们以调用类作为第一个参数被调用
    @classmethod
    def get_species(cls):
        return cls.species

    # 在没有类或实例引用的情况下调用静态方法
    @staticmethod
    def grunt():
        return "*grunt*"

    # 属性就像getter。
    # 它将方法age()转换为同名的只读属性。
    # 但是,在Python中不需要编写琐碎的getter和setter。
    @property
    def age(self):
        return self._age

    # 这允许设置属性
    @age.setter
    def age(self, age):
        self._age = age

    # 这允许删除属性
    @age.deleter
    def age(self):
        del self._age


# 当Python解释器读取源文件时,它会执行所有的代码。
# 此检查确保仅在此情况下执行此代码块
# 模块是主程序。
if __name__ == '__main__':
    # 实例化一个类
    i = Human(name="Ian")
    i.say("hi")                     # "Ian: hi"
    j = Human("Joel")
    j.say("hello")                  # "Joel: hello"
    # i和j是Human类型的实例,换句话说:它们是Human对象
    # 调用我们的类方法
    i.say(i.get_species())          # "Ian: H. sapiens"
    # 更改共享属性
    Human.species = "H. neanderthalensis"
    i.say(i.get_species())          # => "Ian: H. neanderthalensis"
    j.say(j.get_species())          # => "Joel: H. neanderthalensis"

    # 调用静态方法
    print(Human.grunt())            # => "*grunt*"

    # 不能使用对象实例调用静态方法
    # 因为i.grunt()会自动将“self”(对象i)作为参数
    print(i.grunt())                # => TypeError: grunt() takes 0 positional arguments but 1 was given

    # 更新此实例的属性
    i.age = 42
    # 获得属性
    i.say(i.age)                    # => "Ian: 42"
    j.say(j.age)                    # => "Joel: 0"
    # 删除属性
    del i.age
    # i.age                         # => this would raise an AttributeError
6.1、Inheritance 继承
####################################################
## 6.1 Inheritance
####################################################

# 继承允许定义继承方法和
# 来自父类的变量。

# 使用上面定义的Human类作为基类或父类,我们可以
# 定义一个子类,超级英雄,它继承了类变量
# "species", "name", 和 "age", 以及方法, 如 如来自Human类的“sing”和“grunt”
# 但也可以有自己独特的属性。

# 为了利用文件模块化,你可以把上面的类放在它们自己的文件中,
# 例如, human.py

# 要从其他文件中导入函数,请使用以下格式
# 从“没有扩展名的文件”中导入“function-or-class”

from human import Human


# 将父类指定为类定义的参数
class Superhero(Human):

    # 如果子类继承了父类的所有定义而不做任何修改,
    # 你可以只使用“pass”关键字(其他什么都不用),
    # 但在这种情况下,它被注释掉了,以允许一个唯一的子类:
    # 通过

    # 子类可以覆盖父类的属性
    species = 'Superhuman'

    # 子类自动继承父类的构造函数(包括其参数),
    # 但也可以定义其他参数或定义并覆盖其方法(如类构造函数)。
    # 这个构造函数继承了“Human”类的“name”参数,
    # 并添加了“super”和“movie”参数:
    def __init__(self, name, movie=False,
                 superpowers=["super strength", "bulletproofing"]):

        # 添加额外的类属性:
        self.fictional = True
        self.movie = movie
        # 注意可变的默认值,因为默认值是共享的
        self.superpowers = superpowers

        # “super”函数允许您访问父类中被子类覆盖的方法,
        # 在本例中是被子类覆盖的方法。
        # 它调用父类构造函数:
        super().__init__(name)

    # 覆写 sing 方法
    def sing(self):
        return 'Dun, dun, DUN!'

    # 添加一个额外的实例方法
    def boast(self):
        for power in self.superpowers:
            print("I wield the power of {pow}!".format(pow=power))


if __name__ == '__main__':
    sup = Superhero(name="Tick")

    # 实例类型检查
    if isinstance(sup, Human):
        print('I am human')
    if type(sup) is Superhero:
        print('I am a superhero')

    # 获取getattr()和super()使用的方法解析搜索顺序。
    # 该属性是动态的,可以更新
    print(Superhero.__mro__)    # => (<class '__main__.Superhero'>,
                                # => <class 'human.Human'>, <class 'object'>)

    # 调用父方法,但使用自己的类属性
    print(sup.get_species())    # => Superhuman

    # 调用覆写方法
    print(sup.sing())           # => Dun, dun, DUN!

    # 从 Human 调用方法
    sup.say('Spoon')            # => Tick: Spoon

    # 调用仅存在于 Superhero 中的方法 
    sup.boast()                 # => I wield the power of super strength!
                                # => I wield the power of bulletproofing!

    # 继承的类属性
    sup.age = 31
    print(sup.age)              # => 31

    # 属性只存在于 Superhero
    print('Am I Oscar eligible? ' + str(sup.movie))
6.2、Multiple Inheritance 多重继承
####################################################
## 6.2 Multiple Inheritance
####################################################

# 另一个类的定义
# bat.py
class Bat:

    species = 'Baty'

    def __init__(self, can_fly=True):
        self.fly = can_fly

    # 这个类还有一个say方法
    def say(self, msg):
        msg = '... ... ...'
        return msg

    # 以及它自己的方法
    def sonar(self):
        return '))) ... ((('

if __name__ == '__main__':
    b = Bat()
    print(b.say('hello'))
    print(b.fly)


# 又是一个继承自超级英雄(Superhero)和蝙蝠(Bat)的类定义
# superhero.py
from superhero import Superhero
from bat import Bat

# 将蝙蝠侠定义为一个既继承了超级英雄又继承了蝙蝠的子类
class Batman(Superhero, Bat):

    def __init__(self, *args, **kwargs):
        # 通常要继承属性,你必须调用超:
        # super(Batman, self).__init__(*args, **kwargs)      
        # 但是,我们在这里处理的是多重继承,
        # super()只适用于MRO列表中的下一个基类。
        # 因此,我们明确地将所有祖先称为_init__。
        # T使用*args和**kwargs允许以一种干净的方式传递参数,
        # 每个父类“剥下一层洋葱”。
        Superhero.__init__(self, 'anonymous', movie=True, 
                           superpowers=['Wealthy'], *args, **kwargs)
        Bat.__init__(self, *args, can_fly=False, **kwargs)
        # 覆盖name属性的值
        self.name = 'Sad Affleck'

    def sing(self):
        return 'nan nan nan nan nan batman!'


if __name__ == '__main__':
    sup = Batman()

    # 获取getattr()和super()使用的方法解析搜索顺序。
    # 此属性是动态的,可以更新
    print(Batman.__mro__)       # => (<class '__main__.Batman'>, 
                                # => <class 'superhero.Superhero'>, 
                                # => <class 'human.Human'>, 
                                # => <class 'bat.Bat'>, <class 'object'>)

    # 调用父方法,但使用自己的类属性
    print(sup.get_species())    # => Superhuman

    # 调用覆盖方法
    print(sup.sing())           # => nan nan nan nan nan batman!

    # 从Human调用方法,因为继承顺序很重要
    sup.say('I agree')          # => Sad Affleck: I agree

    # 调用仅存在于第二个祖先中的方法
    print(sup.sonar())          # => ))) ... (((

    # 继承的类属性
    sup.age = 100
    print(sup.age)              # => 100

    # 继承了第二祖先的属性,其默认值被覆盖。
    print('Can I fly? ' + str(sup.fly)) # => Can I fly? False

七、Advanced 优化

####################################################
## 7. Advanced
####################################################

# 生成器帮助您生成惰性代码。
def double_numbers(iterable):
    for i in iterable:
        yield i + i

# 生成器是内存有效的,因为它们只加载需要的数据
# 处理iterable中的下一个值。
# 这使得它们可以在非常大的值范围内执行操作。
# 注:Python 3中的range替换xrange。  `range` replaces `xrange`  in Python 3.
for i in double_numbers(range(1, 900000000)):  # `range` is a generator.
    print(i)
    if i >= 30:
        break

# 就像您可以创建列表理解一样,您也可以创建生成器理解。
values = (-x for x in [1,2,3,4,5])
for x in values:
    print(x)  # prints -1 -2 -3 -4 -5 to console/terminal

# 您还可以直接将生成器理解转换为列表。
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
print(gen_to_list)  # => [-1, -2, -3, -4, -5]


# 修饰符
# 在这个例子中' beg ' wrap ' say '。 如果 say_please 是真的,
# 那么它将更改返回的消息。
from functools import wraps


def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, "Please! I am poor :(")
        return msg

    return wrapper


@beg
def say(say_please=False):
    msg = "Can you buy me a beer?"
    return msg, say_please


print(say())                 # Can you buy me a beer?
print(say(say_please=True))  # Can you buy me a beer? Please! I am poor :(
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值