Python知识回顾(基于《笨方法学Python3》)——ex27-ex45

ex27——记住逻辑关系

  • 这一小节意在学会一些逻辑判断

and | 与
or | 或
not | 非
!= | 不等于
== | 等于
>= | 大于等于
< = | 小于等于
True | 真
False | 假

ex28——布尔表达式练习

这一节是对ex27的巩固,意在增加对逻辑关系的理解

ex29——if语句

这一节是为了理解if语句的格式

people = 20
cats = 30
dogs = 15


if people < cats:
    print("Too many cats! The world is doomed!")

if people > cats:
    print("Not many cats! The world is saved!")

if people > dogs:
    print("The world is dry!")

ex30——else和if

这一节意在理解 else、elif 和 if 之间的联系

people = 30
cars = 40
trucks = 15


if cars > people:
    print("We should take the cars.")
elif cars < people:
    print("We should not take the cars.")
else:
    print("We can't decide.")

ex31——作出决定

通过 if、 else 和 elif 来设计一个小游戏,加深对 if 、else、 elif 的理解

ex32——循环和列表

熟悉列表的格式和作用
这里注意,数字在列表不需要加 ‘ ’ ,但文字和字母需要

for i in range(1, 3) # 在这里只循环2次而非三次,即实际上到2就停了

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

#This first kind of for-loop through a list
for number in the_count:
    print(f"This is count {number}")

#same as above
for fruit in fruits:
    print(f"A fruit of type :{fruit}")

# also we can go through mixed lists too
# notice we have to use {} since we don't know what's in it
for i in  change:
    print(f"I got {i}")

ex33——while 循环

对while循环格式的理解

i = 0
numbers = []

while i < 6:
    print(f"At the top i is  {i}")
    numbers.append(i)

    i = i + 1
    print("Numbers now",numbers)
    print(f"At the bottom i is {i}")

ex34——访问列表的元素

知道编程中元素的排序下标为 0、1、2、3、4、5、6、7、8

ex35——分支和函数

通过编写一个游戏加深对函数的理解

def gold_room():
    print("This room is full of gold. How much do you take?")

    choice = input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")

注意,python中以缩进来划分代码块

ex36——设计和调试

知道如何调试代码
这里可以用 print()语句进行调试

ex37——复习各种符号(略)

ex38——列表的操作

熟悉一些对列表的基本操作

A.split(‘’):将语句A切片
A.pop() : 弹出列表元素
A.append() : 将A中加入元素
print(‘–‘.join(A)) : 打印时在A中元素之间打印加上–
print(’#’.join(stuff[3:5]) : 打印下标为3和下标为4的元素,并且中间用#隔开

ten_things = "Apples Orange Crows Telephone Light Sugar"

print("Wait there are not 10 things in that list. Let's fix that.")

stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Gril", "Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop()
    print("Adding:",next_one)
    stuff.append(next_one)
    print(f"There are {len(stuff)} items now.")

print("There we go:",stuff)

print("There's do something with stuff.")

print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print('_____'.join(stuff))
print('#'.join(stuff[3:5]))

ex39——字典

列表中通过数字的下标找到元素

things = [‘a’, ‘b’, ‘c’, ‘d’]
其中print(things[1]) 打印出 b 元素

字典则是类似于显示中的字典

states = {
‘Oregon’: ‘OR’,
‘Florida’: ‘FL’,
‘California’: ‘CA’,
‘New York’: ‘NY’,
‘Michigan’: ‘MI’,
}
其中 print(states[Oregon]) 打印出 OR 元素,即一一对应

ex40——模块、类和对象

模块
定义:

  • 模块是包含函数和变量的Python文件(.py文件)
  • 可以导入这个文件
  • 导入后可以访问模块中的函数和变量
    例:我有个文件stuff.py
def apple():
	print("I am apples!")

我可以通过以下方法进行调用

import stuff
stuff.apple()

不仅可以调用其中函数,还可以调用其中的参量

class Song(object):

    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

以上代码就定义了一个叫 Song 的类

对象

happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])

以上的代码声明了一个对象
对象和模块差不多
例:上面可以通过 happy_bday.sing_me_a_song() 来调用函数

ex41——学习面向对象的术语

定义:

  • 类(class):告诉Python创建类型的东西
  • 对象(object):两个意思,即最基本的东西,或者某样东西的实例
  • 实例(instance):这是让Python创建一个类时得到的东西
  • def:在类中定义函数的方法
  • self:在类的函数中,self指代被访问的对象或者实例的一个变量
  • 继承(inheritance):指一个类可以继承另一个类的特性,和父子关系类似
  • 组合(composition):指一个类可以将别的类作为它的部件构建起来,有点儿像车子和车轮的关系
  • 属性(attribute):类的一个属性,它来自于组合,而且通常是一个变量
  • 是什么(is-a):用来描述继承关系,例:Salmon is-a Fish (鲑鱼是一种鱼)
  • 有什么(has-a):用来描述某个东西是由另外一些东西组成的,或者某个东西有某个特征,例:Salmon has-a mouth(鲑鱼有一张嘴)

一些概念:

  • class X(Y):创建了一个叫X的类,它是 Y 的一种
  • class X(object): def init(self, J):类 X 有一个__init__,它接受 self 和 J 作为参数
  • class X(object): def M(self, J):类 X 有一个名为M的函数,它接收 self 和 J 作为参数
  • foo = X():将 foo 设为类 X 的一个实例
  • foo.M(J):从 foo 中找到 M 函数,并且使用 self 和 J 参数调用它
  • foo.K = Q:从 foo 中获取 K 属性,并将其设为Q

将以上的概念和定义记忆理解

ex42——对象、类及从属关系

通过编写一些代码加深对对象、类及从属关系的理解

ex43——基本的面向对象分析和设计

即写一个游戏,加深理解

ex44——继承与组合

继承
定义:

  • 子类上的动作完全等同于父类上的动作(隐式继承)
  • 子类上的动作完全覆盖了父类上的动作(显式覆盖)
  • 子类上的动作部分替换了父类上的动作(在运行前或运行后替换)

隐式继承
在父类里定义了一个函数但没有在子类中定义时的隐式继承

class Parent(object):

    def implicit(self):
        print("PARENT implicit()")

class Child(Parent):
	pass

dad = Parent()
son = Child()

dad.implicit()
son.implicit()

这个歌时候的打印结果应该是

PARENT implicit()
PARENT implicit()

显式覆盖
要使子类中的函数有不同的行为,这种情况下隐式继承是做不到的。这时需要在子类中定义一个与父类中同名的函数即可。

class Parent(object):

    def override(self):
        print("PARENT override()")

class Child(Parent):

    def altered(self):
        print("CHILD override()")
        
dad = Parent()
son = Child()

dad.override()
son.override()

结果是

PARENT override()
PARENT override()

在运行前或运行后替换
即想要修改函数,又想要父类中的函数,首先要像上面一样进行覆盖,之后调用super()函数进行调用父类的函数

class Parent(object):

    def altered(self):
        print("PARENT altered()")

class Child(Parent):
    def altered(self):
        print("Child")
        super(Child, self).altered()
        print("Child 2 ")

dad = Parent()
son = Child()

dad.altered()
son.altered()

结果是

PARENT altered()
Child
PARENT altered()
Child 2

从结果中我们可以看到,函数super()使得回到了Child的父类中调用了altered()函数进行打印

ex45——你来制作一款游戏(略)

意在巩固代码能力

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值