2.2请练习定义一个动物类,并创建出两个实例dog, cat,打印实例,再比较两个实例是否相等
class Animal(object):pass
dog = Animal()
cat = Animal()
print(cat)
print(dog==cat)
<__main__.Animal object at 0x00000189935BD280>
False
2.3请定义一个动物类,并创建出两个实例dog, cat,分别赋予不同的名字和年龄。
class Animal(object):pass
dog = Animal()
cat = Animal()
dog.name = 'xiaohuang'
dog.age = 1
cat.name = 'xiaohua'
cat.age = 2
2.4请定义一个动物类,抽象出名字、年龄两个属性,并实例化两个实例dog, cat。
class Animal(object):def __init__(self,name,age):self.name = nameself.age = age
dog = Animal('xiaohuang',3)
cat = Animal('xiaohua',4)
print(dog.name,dog.age)
print(cat.name,cat.age)
xiaohuang 3
xiaohua 4
2.5请给 Animal类添加一个类属性 count,每创建一个实例,count 属性就加 1,这样就可以统计出一共创建了多少个 Animal的实例。
class Animal(object):location = 'China'count = 0def __init__(self,name,age):self.name = nameself.age = ageAnimal.count += 1dog = Animal('xiaohuang',4)
cat = Animal('xiaohua',3)
pig = Animal('xiaozhu',6)
print(dog.name,dog.age)
print(cat.name,cat.age)
print(pig.name,pig.age)
print(Animal.count)
xiaohuang 4
xiaohua 3
xiaozhu 6
3
2.6请把上节的 Animal类属性 count 改为 __count,再试试能否从实例和类访问该属性。
class Animal(object):__count = 0def __init__(self,name):Animal.__count = Animal.__count + 1self.name = nameprint('内部:{}'.format(Animal.__count))p1 = Animal('Cat')p2 = Animal('Dog')
内部:1
内部:2
2.7请给Animal类的__init__方法中添加name和age参数,并把age绑定到__age属性上,看看外部是否能访问到。(很显然访问不到,程序报错)
class Animal(object):def __init__(self,name,age):self.name = nameself.__age = agedog = Animal('xiaohuang',12)
print(dog.name,dog.__age)
---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)Input In [72], in <cell line: 7>()4         self.__age = age6 dog = Animal('xiaohuang',12)
----> 7 print(dog.name,dog.__age)AttributeError: 'Animal' object has no attribute '__age'
2.8把Animal类的age、name、localtion定义成私有属性,并定义对应的方法修改和获取他们的值。
class Animal(object):def __init__(self,name,age,location):self.__name = nameself.__age = ageself.__location = locationdef set_name(self,name):self._name = namedef get_name(self):return self.__namedef set_age(self,age):self._age = agedef get_age(self):return self._agedef set_location(self,location):self_location = locationdef get_location(self):return self._locationdog = Animal('xiaohuang',2,'GuangDong')
print(dog.get_name())
dog.set_age(5)
print(dog.get_age())
xiaohuang
5
2.9如果将类属性count改为私有属性__count,则外部无法获取__count,但是可以通过一个类方法获取,请编写类方法获得__count值。
class Animal(object):__location = 'Asia'__count = 0def __init__(self,name,age):self.name = nameself.age = ageAnimal.__count += 1@classmethoddef set_location(cls,location):cls.__location = location@classmethoddef get_location(cls):return cls.__location@classmethoddef get_count(cls):return cls.__countdog = Animal('xiaohua',4)print(Animal.get_location())
Animal.set_location('China')
print(Animal.get_location())print(Animal.get_count())
Asia
China
1
3.2请参考Student类,编写Teacher类,老师拥有任教某个科目的属性。
class Person(object):def __init__(self,name,gender):self.name = nameself.gender = genderclass Student(Person):def __init__(self,name,gender,score):super(Student,self).__init__(name,gender)self.score = scorestudent = Student('julia','girl',18)
print(student.name)
print(student.gender)
print(student.score)class Teacher(Person):def __init__(self,name,gender,course):super(Teacher,self).__init__(name,gender)self.course = courseteacher = Teacher('Jue','boy','MATH')
print(teacher.name)
print(teacher.gender)
print(teacher.course)
julia
girl
18
Jue
boy
MATH
3.3请根据继承链的类型转换,依次思考 t 是否是 Person,Student,Teacher,object 类型,并使用isinstance()判断来验证您的答案。
class Person(object):def __init__(self,name,gender):self.name = nameself.gender = genderclass Student(Person):def __init__(self,name,gender,score):super(Student,self).__init__(name,gender)self.score = scoreclass Teacher(Person):def __init__(self,name,gender,course):super(Teacher,self).__init__(name,gender)self.course = coursep = Person('Bob','male')
s = Student('Julie','female',56)
t = Teacher('Tim','male','English')
print(isinstance(t,Person))
print(isinstance(t,Student))
print(isinstance(t,Teacher))
print(isinstance(t,object))
True
False
True
True
3.4已知类Student、Teacher继承Person类,技能类BasketballMixin、FootballMixin继承SkillMixin类,请通过多重继承,分别定义“会打篮球的学生”和“会踢足球的老师”。
class Person(object):def __init__(self,name,gender):self.name = nameself.gender = genderclass SkillMixin(object):def __init__(self,skill):self.skill = skilldef say(self):print("技能是%s"%(self.skill))class BasketballMixin(SkillMixin):def __init__(self,skill):super(BasketballMixin,self).__init__(skill)class FootballMixin(SkillMixin):def __init__(self,skill):super(FootballMixin,self).__init__(skill)class Student(Person,BasketballMixin):def __init__(self,name,gender,score,skill):super(Student,self).__init__(name,gender)BasketballMixin.__init__(self, skill)self.score = scoredef say(self):print("学生叫%s,性别%s,考试分数为%d, 喜欢%s" %(self.name, self.gender, self.score, self.skill))class Teacher(Person,FootballMixin):def __init__(self, name, gender, subject,skill):super(Teacher, self).__init__(name, gender)FootballMixin.__init__(self,skill)self.subject = subjectdef say(self):print("老师叫%s,性别%s,教学科目为%s, 喜欢%s" %(self.name, self.gender, self.subject,self.skill))s = Student('小明','男',45,'Basketball')
s.say()
t = Teacher('小王','男','MATH','Football')
t.say()
学生叫小明,性别男,考试分数为45, 喜欢Basketball
老师叫小王,性别男,教学科目为MATH, 喜欢Football
3.5对于Person类的定义,希望除了name和gender外,可以提供任意额外的关键字参数,并绑定到实例,请修改 Person 的__init__()定义,完成该功能。
class Person(object):def __init__(self, name, gender,**kw):self.name = nameself.gender = genderfor k,v in kw.items():setattr(self,k,v)
p = Person('Alice','girl',age=13,course='Python')
print(p.age)
print(p.course)
13
Python
4.2请给Student 类定义__str__和__repr__方法,使得能打印出’Student: name, gender, score’。
class Person(object):def __init__(self,name,gender):self.name = nameself.gender = genderclass Student(Person):def __init__(self,name,gender,score):super(Student,self).__init__(name,gender)self.score = scoredef __str__(self):return 'Student:{},{},{}'.format(self.name,self.gender,self.score)def __repr__(self):return 'STUDENT:{},{},{}'.format(self.name,self.gender,self.score)student = Student('xiaohua','boy',78)
print(student)
print('%r'%student)
print(str(student))
print(repr(student))
Student:xiaohua,boy,78
STUDENT:xiaohua,boy,78
Student:xiaohua,boy,78
STUDENT:xiaohua,boy,78
4.3斐波那契数列是由 0, 1, 1, 2, 3, 5, 8…构成。请编写一个Fib类,Fib(10)表示数列的前10个元素,print Fib(10) 可以打印出数列的前 10 个元素,len(Fib(10))可以正确返回数列的个数10。
class Fib(object):def __init__(self,num):self.Lis = []self.num = numa = 0b = 1for i in range(num):self.Lis.append(a)a = bb = a+bdef __len__(self):return self.numdef __str__(self):return str(self.Lis)f = Fib(10)
print(f)
print(len(f))
[0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
10
4.4Rational类虽然可以做加法,但无法做减法、乘法和除法,请继续完善Rational类,实现四则运算。
class Rational(object):def __init__(self,p,q):self.p = pself.q = qdef __add__(self,r):return Rational(self.p*r.q+self.q*r.p,self.q*r.q)def __sub__(self,r):return Rational(self.p*r.q-self.q*r.p,self.q*r.q)def __mul__(self,r):return Rational(self.p*r.p,self.q*r.q)def __truediv__(self,r):return Rational(self.p*r.q,self.q*r.p)def __str__(self):return '{}/{}'.format(self.p,self.q)r1 = Rational(1,2)
r2 = Rational(2,3)
print(r1+r2)
print(r1-r2)
print(r1*r2)
print(r1/r2)
7/6
-1/6
2/6
3/4
4.5假设Person类通过__slots__定义了name和gender,请在派生类Student中通过__slots__继续添加score的定义,使Student类可以实现name、gender和score 3个属性。
class Person(object):__slots__ = ('name','gender')def __init__(self,name,gender):self.name = nameself.gender = gender
class Student(Person):__slots__ = ('name','gender','score')def __init__(self,name,gender,score):super(Student,self).__init__(name,gender)self.score = score
st = Student('xiaohua','boy',67)
st.gender = 'girl'
st.score = 90
print(st)
<__main__.Student object at 0x0000018993F449A0>
4.6请实现前面介绍过的斐波那契数列类Fib,加入__call__方法,使得调用的方式如下简单。

f = Fib()
print f(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

class Fib(object):def __init__(self):passdef __call__(self,num):self.Lis = []a = 0b = 1for i in range(num):self.Lis.append(a)a = bb = a+breturn self.Lisf = Fib()
print(f(10))
[0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
5.2定义一个公共模块common.py,在common.py中,包含公共函数say_hello(name),它接受一个参数,输出:Hello 的结果。
def say_hello(name):print('Hello{}'.format(name))
say_hello("xiaohua")
Helloxiaohua
5.3math模块还提供了非常多的数学计算函数,比如:正弦sin()函数,余弦cos()函数,请使用两种导入的方式,使用这两个函数。
import math
print(math.sin(0))
print(math.cos(0))from math import sin,cos
print(sin(90))
print(cos(90))
0.0
1.0
0.8939966636005579
-0.4480736161291701
5.4Python的sys.path返回的是一个路径列表,因此可以操作列表里面的元素,请通过sys.path增加路径’…/',使得在运行时,可以导入当前目录上级目录的包。
import sys
print(sys.path)
sys.path.append('../')
print(dir(sys.path))
['C:\\Users\\Administrator\\JUPYTERLAB', 'D:\\Anaconda3\\python39.zip', 'D:\\Anaconda3\\DLLs', 'D:\\Anaconda3\\lib', 'D:\\Anaconda3', '', 'D:\\Anaconda3\\lib\\site-packages', 'D:\\Anaconda3\\lib\\site-packages\\win32', 'D:\\Anaconda3\\lib\\site-packages\\win32\\lib', 'D:\\Anaconda3\\lib\\site-packages\\Pythonwin', '../']
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
5.5requests是一个好用的HTTP模块,请通过pip安装该模块。

pip install request

6.1eval()函数可以把字符串转换为等值的结果,比如eval(‘1+1’),得到结果为2。请使用eval实现一个简单的计算器,可以输入表达式并打印计算结果。
while True:s = input('>>> ')if s == 'break':breakresult = eval(s)print(result)
>>> Traceback (most recent call last):File D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3369 in run_codeexec(code_obj, self.user_global_ns, self.user_ns)Input In [87] in <cell line: 2>result = eval(s)File <string>^
SyntaxError: unexpected EOF while parsing
6.2请尝试以只读模式打开一个指定绝对路径的文本文件,并正确关闭。
f = open('test.txt','r')
f.close()
6.3请尝试用只读模式打开一个指定绝对路径的二进制文件,并正确关闭。
f = open('test.txt','rb')
f.close()
6.4实现一个read.py文件,把read.py文件的内容打印出来。
f = open('read.py')
content = f.readlines()
print(content)
['read me']
6.5有test.txt文件,包含以下内容:Hello World Hello Python Hello Imooc 请从test.txt文件读取以上内容,并将每一行字符串反转,写入test1.txt文件
f = open('test.txt', 'r')
lines = f.readlines()
f1 = open('test1.txt', 'w')
for line in lines:line = line[::-1]f1.write(line)f1.close()
f.close()
6.6假设test.txt文件有以下内容:Hello World Hello Python Hello Imooc 请将文件的内容重复写一份追加到文件的尾部
with open('test.txt','a+') as f:lines = f.readlines()f.seek(2)f.writelines(lines)
8.2利用上面定义的add(x, y, f)函数,计算根号x+根号y
import math
def add(x,y,f):return f(x)+f(y)
an = add(5,8,math.sqrt)
print(an)
5.06449510224598
8.3假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list:

输入:[‘alice’, ‘BOB’, ‘CanDY’]
输出:[‘Alice’, ‘Bob’, ‘Candy’]

def f(s):return s[0].upper()+s[1:].lower()for item in map(f,['alice','BoB','canDy']):print(item)
Alice
Bob
Candy
8.4Python内置了求和函数sum(),但没有求积的函数,请利用recude()来求积

输入:[1, 3, 5, 7, 9]
输出:13579的结果

import functools
def f(x,y):return x*yprint(reduce(f,[1,3,5,7,9]))
945
8.5请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:1, 4, 9, 16, 25, 36, 49, 64, 81, 100。
import math
def f(x):r = int(math.sqrt(x))return r*r == x
for item in filter(f,range(1,101)):print(item)
1
4
9
16
25
36
49
64
81
100
8.6对字符串排序时,有时候忽略大小写排序更符合习惯。请利用sorted()高阶函数,实现忽略大小写排序的算法。

输入:[‘bob’, ‘about’, ‘Zoo’, ‘Credit’]
输出:[‘about’, ‘bob’, ‘Credit’, ‘Zoo’]

def k(item):return item.lower()print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=k))
['about', 'bob', 'Credit', 'Zoo']
8.7请编写一个函数calc_prod(list_),它接收一个list,返回一个函数,返回函数可以计算参数的乘积。
from functools import reducedef calc_prod(list_):def lazy_prod():def f(x, y):return x * yreturn reduce(f, list_, 1)return lazy_prodf = calc_prod([1, 2, 3, 4])
f()
24
8.8对字符串排序时,有时候忽略大小写排序更符合习惯。请利用sorted()高阶函数和lambda匿名函数,实现忽略大小写排序的算法。

输入:[‘bob’, ‘about’, ‘Zoo’, ‘Credit’]
输出:[‘about’, ‘bob’, ‘Credit’, ‘Zoo’]

sorted(['bob', 'about', 'Zoo', 'Credit'], key=lambda item: item.lower())
['about', 'bob', 'Credit', 'Zoo']
8.9请用functools.partial把这个复杂调用变成一个简单的函数:sorted_ignore_case([‘bob’, ‘about’, ‘Zoo’, ‘Credit’])
import functools
sorted_ignore_case = functools.partial(sorted, key=lambda item: item.lower())
sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
['about', 'bob', 'Credit', 'Zoo']

Python实践-咚咚呛讲师Python进阶教程相关推荐

  1. python动态类型的坑_python进阶教程之动态类型详解

    动态类型(dynamic typing)是Python另一个重要的核心概念.我们之前说过,Python的变量(variable)不需要声明,而在赋值时,变量可以重新赋值为任意值.这些都与动态类型的概念 ...

  2. python 协程爬虫_Python爬虫进阶教程(二):线程、协程

    简介 线程 线程也叫轻量级进程,它是一个基本的CPU执行单元,也是程序执行过程中的最小单元,由线程ID.程序计数器.寄存器集合和堆栈共同组成.线程的引入减小了程序并发执行时的开销,提高了操作系统的并发 ...

  3. python实践意义_在Python学习中过程比结果更有意义

    原标题:在Python学习中过程比结果更有意义 如果人生是一趟旅行,那我们最应该关注的是沿途的风景而不是最终的目的地.对于学习Python而言,提升自身能力.提高处理问题的速度.培养自己勤思考.善于思 ...

  4. python实践心得体会_“Python自然语言实践”——总结(一),实战

    正则表达式在NLP中的基本应用 正则表达式的作用: (1)将文档内容从非结构化转为结构化以便后续的文本挖掘 (2)去除"噪声",在处理大量文本片段的时候,有非常多的文字信息与最终输 ...

  5. Python 学习笔记之字典(进阶篇)

    基础教程介绍了基本概念,特别是对象和类. 进阶教程对基础教程的进一步拓展,说明Python的细节.希望在进阶教程之后,你对Python有一个更全面的认识. 之前我们说了,列表是Python里的一个类. ...

  6. python高级教程_Python高级进阶教程

    这个系列的教程是在刘金玉编程的<零基础python教程>基础上的高级进阶应用. 教程列表: Python高级进阶教程001期 pycharm+anaconda3+pyqt5可视化界面开发环 ...

  7. 机器学习算法与Python实践之(三)支持向量机(SVM)进阶

    机器学习算法与Python实践这个系列主要是参考<机器学习实战>这本书.因为自己想学习Python,然后也想对一些机器学习算法加深下了解,所以就想通过Python来实现几个比较常用的机器学 ...

  8. python模块编程教程_python进阶教程之模块(module)介绍

    我们之前看到了函数和对象.从本质上来说,它们都是为了更好的组织已经有的程序,以方便重复利用. 模块(module)也是为了同样的目的.在Python中,一个.py文件就构成一个模块.通过模块,你可以调 ...

  9. python进阶教程之异常处理

    python进阶教程之异常处理 这篇文章主要介绍了python进阶教程之异常处理,在项目开发中,异常处理是不可或缺的,需要的朋友可以参考下 在项目开发中,异常处理是不可或缺的.异常处理帮助人们debu ...

最新文章

  1. TensorFlow全家桶的落地开花 | 2019 Google开发者日
  2. PHP 学习笔记 01
  3. 人像拍摄时眼部合焦的技巧
  4. HTTP错误汇总及其解决方法
  5. amd显卡风扇调节_非公版才是真爱 讯景XFX RX6800 XT海外版显卡评测
  6. 稳站大屏 AIoT 时代之巅,创维 Swaiot 生态品牌实现全面布局!
  7. 【声源定位】基于matlab不同信噪比下麦克风接收信号【含Matlab源码 546期】
  8. HDC1080介绍与使用
  9. matlab数据转换为tecplot格式[ASCII码格式下的plt文件]
  10. 计算机主机电池馈电,电脑主板电池没电了会出现什么情况?电脑主板电池没电的解决方法...
  11. 20种硬件工程师必知必会基础元器件|最新更新至8.13
  12. 程序员的回忆录(1)-起点
  13. android su文件,Android su开放root权限
  14. weinre远程调试mobile页面
  15. 硬盘质保、保修期网上查询
  16. BZOJ 3698(XWW的难题-上下界网络流+经典建模)
  17. 手势操作TouchAction
  18. Netty保姆级教程(一)IO 演变
  19. 二分查找的魔鬼细节详解
  20. windows和Mac怎么查看ip地址

热门文章

  1. POJ 2886:Who Gets the Most Candies?
  2. SCRIPT5: 拒绝访问
  3. a标签 rel=“external nofollow“ 用法
  4. Codeforces Round #354 (Div. 2)-Theseus and labyrint
  5. 关于计算机的知识作文,计算机想象作文
  6. HTML5期末大作业:关于家乡景点介绍网页设计-------我的家乡金堂(9页) HTML+CSS+JavaScript
  7. python小游戏扫雷怎么玩的技巧_用 Python 实现扫雷小游戏
  8. jquery id选择器获取id值含有特殊字符的方法
  9. 【人工智能】— 不确定性、先验概率/后验概率、概率密度、贝叶斯法则、朴素贝叶斯 、最大似然估计
  10. 已向反垄断法妥协!谷歌应用商店抽成减半,苹果还会远吗?