首页 文章 精选 留言 我的

精选列表

搜索[快速入门],共10000篇文章
优秀的个人博客,低调大师

Java入门系列-18-抽象类和接口

抽象类 在第16节继承中,有父类 People People people=new People(); people.sayHi(); 实例化People是没有意义的,因为“人”是一个抽象的概念。 怎么才能避免父类的实例化呢?使用 abstract 关键字修饰类(抽象类)。 抽象父类 public abstract class People { private String name; public People(String name) { super(); this.name = name; } //人类共有方法 哭 public void cry() { System.out.println("呜呜"); } //抽象方法 不做具体实现 public abstract void sayHi(); public String getName() { return name; } public void setName(String name) { this.name = name; } } 子类:Chinese.java //中国人 public class Chinese extends People{ public Chinese(String name) { super(name); } //必须实现 @Override public void sayHi() { System.out.println(this.getName()+":你好!"); } } 子类:Britisher.java //英国人 public class Britisher extends People{ public Britisher(String name) { super(name); } @Override public void sayHi() { System.out.println(this.getName()+":Hello!"); } } 测试类 public class TestPeople { public static void main(String[] args) { //People people=new People("张三");//去掉注释试试 People chinese=new Chinese("张三"); chinese.sayHi(); People britisher=new Britisher("John"); britisher.sayHi(); } } 被关键字 abstract 修饰的类是抽象类,抽象类不能实例化 被关键字 abstract 修饰的方法是抽象方法,抽象方法没有方法体 抽象方法必须在抽象类里 抽象方法必须在子类中被实现,除非子类是抽象类 抽象方法没有方法体 public abstract void sayHi(); 注意:被 abstract 修饰后不能使用 final 修饰! 接口 如何实现防盗门这个类?门有“开”和“关”的功能,锁有“上锁”和“开锁”的功能,将门和锁分别定义为抽象类。但是防盗门可以继承门的同时又继承锁吗?不能,防盗门不是锁,不符合 is a 的关系而且Java只支持单继承。 接口的语法 public interface MyInterface { public abstract void foo(); } 接口可以认为是纯粹的抽象类 接口中的方法都是抽象方法 (public abstract) 接口不可以被实例化 实现类必须实现接口中的所有方法 接口中的变量都是静态常量 接口之间可以互相继承(extedns),类只能实现接口(implements) 一个类可以继承一个父类,实现多个接口 演示接口的继承及实现接口 父接口:A.java public interface A { void methodA(); } 子接口:B.java public interface B extends A{ void methodB(); } 接口的实现类:C.java public class C implements B{ @Override public void methodA() { } @Override public void methodB() { } } 接口表示能力 面向接口编程时,关心实现类有何能力,而不关心实现细节。面向接口的约定而不考虑接口的具体实现。 在鸟类中,白鹭可以飞,鸵鸟不能飞,所以在这里飞是一种能力,下面看一下代码的设计。 飞行接口:Fly.java //表示飞行能力 public interface Fly { /** * 飞行 */ public abstract void fly(); } 游泳接口:Swim.java //表示游泳能力 public interface Swim { public abstract void swim(); } 鸟类:Bird.java //抽象鸟类 重用代码 public abstract class Bird { /** * 下蛋 */ public void layEggs() { System.out.println("产出一枚蛋"); } } 白鹭类:Egret.java //白鹭类 public class Egret extends Bird implements Fly,Swim{ @Override public void fly() { System.out.println("使劲煽动翅膀后起飞"); } @Override public void swim() { System.out.println("漂在了水面上,轻松的游来游去"); } } 鸵鸟类:Ostrich.java //鸵鸟类 public class Ostrich extends Bird implements Swim{ @Override public void swim() { System.out.println("漂在了水面了,开始游动"); } } 测试类 public class TestBird { public static void main(String[] args) { Egret egret=new Egret(); egret.swim(); egret.fly(); Ostrich ostrich=new Ostrich(); ostrich.swim(); } } 接口表示约定 在生活中,我们使用的插座,规定了两个接头剪得额定电压、两个接头间的距离、接头的形状。 在代码中约定体现在接口名称和注释上 下面使用面向接口编程实现一台计算机的组装,计算机的组成部分有:CPU、硬盘、内存。 先创建 CPU、硬盘、内存接口 package computer; /** * CPU 接口 * @author Jack * */ public interface CPU { /** * 获取CPU品牌 * @return */ String getBrand(); /** * 获取CPU主频 * @return */ Float getFrequency(); } package computer; /** * 硬盘接口 * @author Jack * */ public interface HardDisk { /** * 获取硬盘容量 * @return */ int getCapacity(); } package computer; /** * 内存接口 * @author Jack * */ public interface EMS { /** * 获取内存容量 * @return */ int getSize(); } 将接口设计到计算机类中 package computer; /** * 计算机类 * @author Jack * */ public class Computer { private CPU cpu;//cpu接口 private HardDisk hardDisk;//硬盘接口 private EMS ems;//内存接口 public Computer() { } public Computer(CPU cpu, HardDisk hardDisk, EMS ems) { super(); this.cpu = cpu; this.hardDisk = hardDisk; this.ems = ems; } public CPU getCpu() { return cpu; } public void setCpu(CPU cpu) { this.cpu = cpu; } public HardDisk getHardDisk() { return hardDisk; } public void setHardDisk(HardDisk hardDisk) { this.hardDisk = hardDisk; } public EMS getEms() { return ems; } public void setEms(EMS ems) { this.ems = ems; } } 创建 CPU、硬盘、内存接口的实现 package computer.impl; import computer.CPU; /** * 英特尔 CPU * @author Jack * */ public class IntelCPU implements CPU{ @Override public String getBrand() { return "英特尔"; } @Override public Float getFrequency() { return 2.3f; } } package computer.impl; import computer.HardDisk; /** * 闪迪硬盘 * @author Jack * */ public class SanDisk implements HardDisk{ @Override public int getCapacity() { return 3000; } } package computer.impl; import computer.EMS; /** * 金士顿 内存 * @author Jack * */ public class JSDEMS implements EMS{ @Override public int getSize() { return 4; } } 完成计算机及组件的组装进行测试 package computer; import computer.impl.IntelCPU; import computer.impl.JSDEMS; import computer.impl.SanDisk; public class TestComputer { public static void main(String[] args) { CPU cpu=new IntelCPU();//创建CPU HardDisk sanDisk=new SanDisk();//创建硬盘 EMS jsdEMS=new JSDEMS();//创建内存 Computer computer=new Computer(cpu,sanDisk,jsdEMS); System.out.println("CPU型号:"+computer.getCpu().getBrand()); System.out.println("硬盘容量:"+computer.getHardDisk().getCapacity()+" GB"); System.out.println("内存容量:"+computer.getEms().getSize()+" GB"); } } 接口总结 接口有比抽象类更好的特性: 1.可以被多继承 2.设计和实现完全分离 3.更自然的使用多态 4.更容易搭建程序框架 5.更容易更换实现 搜索关注公众号「享智同行」,第一时间获取技术干货

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第8章习题

#8-1消息:编写一个名为display_message()的函数,它打印一个句子,指出你 #在本章学的是什么。调用这个函数,确认显示的消息正确无误。 def display_message(): print("你正在学的是第八章,函数。") display_message() #8-2 喜欢的图书:编写一个名为favorite_book()的函数,其中包含一个名为 #title的形参。这个函数打印一条消息,如One of my favorite books is #Alice in Wonderland。调用这个函数,并将一本图书的名称作为实参传递给它。 def favorite_book(title): print("One of my favorite books is " + title.title() + ".") favorite_book("calabash brothers") #8-3T恤:编写一个名为make_shirt()的函数,它接受一个尺码以及要印到T恤上 #的字样。这个函数应打印一个句子,概要地说明T恤的尺码和字样。 def make_shirt(size, logo): print("\nThe dress is in size " + str(size) + ".") print("The inscription on The t-shirt is" + logo.title()) make_shirt(25, 'The dog egg') make_shirt(logo = 'The cat egg', size = 26) #8-4大号T恤:修改函数make_shirt(),使其在默认情况下制作一件印有字样“I #lovePython”的大号T恤。调用这个函数来制作如下T恤:一件印有默认字样的大号T恤、 #一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。 def make_shirt(size, logo = 'I love Python'): print("\nThe dress is in size " + str(size) + ".") print("The inscription on The t-shirt is" + logo.title()) make_shirt(size = 'x') make_shirt(size = 'l') make_shirt('l', logo = 'The dog egg') #8-5城市:编写一个名为describe_city()的函数,它接受一座城市的名字以及该城市所属的 #国家。这个函数应打印一个简单的句子,如Reykjavik is in Iceland。给用于存储国家 #的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。 def describe_city(name, country = 'US'): print(name.title() + " is in " + country.title()) describe_city('washington') describe_city('chengdu', country = 'china') describe_city(name = 'paris', country = 'france') #8-6 城市名:编写一个名为city_country()的函数,它接受城市的名称及其所属的 #国家。这个函数应返回一个格式类似于下面这样的字符串:"Santiago, Chile" def city_country(name, country): full_name = name + ' ' + country return full_name.title() location = city_country('beijing', 'chine') print(location) location = city_country('Gibraltar', 'england') print(location) location = city_country('copenhagen', 'Denmark') print(location) #8-7专辑:编写一个名为make_album()的函数,它创建一个描述音乐专辑的字典。这个函数 #应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示 #不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。 def make_album(singerName, albumName, songsNumber = ''): if songsNumber: summarize = { 'name':singerName, 'album':albumName, 'number':songsNumber } else: summarize = {'name':singerName, 'album':albumName} return summarize albumSummarize = make_album('Nicolas Errera', 'The Butterfly') print(albumSummarize) albumSummarize = make_album('muse', 'Unintended',12) print(albumSummarize) albumSummarize = make_album('The Beatles', 'Hey Jude',9) print(albumSummarize) #8-8用户的专辑:在为完成练习8-7编写的程序中,编写一个while循环,让用户输 #入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album(), #并将创建的字典打印出来。在这个while循环中,务必要提供退出途径. def make_album(singerName, albumName, songsNumber = ''): if songsNumber: summarize = { 'name':singerName, 'album':albumName, 'numbers':songsNumber } else: summarize = {'name':singerName, 'album':albumName} return summarize while True: singer = input("输入歌手名字(输入'q'即可退出)") if singer == 'q': break album = input("输入专辑名字(输入'q'即可退出)") if album == 'q': break number = input("输入歌曲数量(输入'q'即可退出)") if number == 'q': break albumSummarize = make_album(singer, album, number) print(albumSummarize) #8-9魔术师:创建一个包含魔术师名字的列表,并将其传递给一个名 #为show_magicians()的函数,这个函数打印列表中每个魔术师的名字。 def shou_magicians(names): for name in names: print(name) magicians = ['wwz','zzq','llo'] shou_magicians(magicians) #8-10了不起的魔术师:在你为完成练习8-9而编写的程序中,编写一个名 #为make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入 #字样“theGreat”。调用函数show_magicians(),确认魔术师列表确实变了。 def make_great(names, roll): while names: name = names.pop() print(name + ' the great.') roll.append(name) magicians_names = ['wwz','zzq','llo'] roll_names = [] make_great(magicians_names, roll_names) print(magicians_names) print(roll_names) #8-12 三明治:编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只 #有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治 #进行概述。调用这个函数三次,每次都提供不同数量的实参。 def add_ingredients(ingredients): print('The side dish you add to your sandwich is ' + ingredients.title()) add_ingredients('egg') add_ingredients('beef') add_ingredients('cheese') #8-13 用户简介:复制前面的程序user_profile.py,在其中调用build_profile()来 #创建 有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。 def build_profile(first, last, **user_info): """创建一个字典,其中包含我们知道的有关用户的一切""" profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('w', 'zc', location='guangyuan', field='game', gender='man') print(user_profile) #8-14 汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造 #商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及 #两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用: def make_car(manufacturer, model, **number): profile = {} profile['制造商'] = manufacturer profile['型号'] = model for key, value in number.items(): profile[key] = value return profile car = make_car( '宝马', '越野', 颜色='银色', 配置='中配', 安全性='优', 舒适性='5星', ) print(car) #8-15 打印模型:将示例print_models py中的函数放在另一个名为printing_functions.py #的文件中;在print_models.py的开头编写一条import语句,并修改这个文件以使用导入的函数。 ''' # printing_functions.py中的代码 def print_models(unprinted_designs, completed_models): """ 模拟打印每个设计,直到没有未打印的设计为止 打印每个设计后,都将其移到列表completed_models中 """ while unprinted_designs: current_design = unprinted_designs.pop() # 模拟根据设计制作3D打印模型的过程 print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): """显示打印好的所有模型""" print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)''' import printing_functions as spam unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] spam.print_models(unprinted_designs, completed_models) spam.show_completed_models(completed_models) #8-16 略 #8-17 略

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第7章习题

#7-1汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息, #如“LetmeseeifIcanfindyouaSubaru”。 car = input() print("Let me see if I can find you a" + car + ".") #7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息, #指出没有空桌;否则指出有空桌。 message = int(input("请问您们用餐的有几位?")) if message > 8: print("抱歉,8个位置以上的位置没有空余的了。") elif message <= 0: print("就餐人数不能少于一个人。") else: print("您好,还有位置。") #7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是10的整数倍。 number = int(input("输入一个数字,我会告诉您,这个数字是否是10的倍数")) if number%10 == 0: print("太棒了!您输入的数字是" + str(number) + ",它是10的倍数。") else: print("真遗憾!您输入的数字是" + str(number) + ",它不是10的倍数。") #7-4比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit'时 #结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料 while True: x = input("请添加披萨的配菜!(输入“quit”退出)") if x != 'quit': print("已为您披萨添加:" + x + "。") else: break #7-5电影票:有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的 #观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用户的年龄, #并指出其票价 age = '' active = True while age != 'qiut': age = input("您好,请问您的年龄是多少?") if age == 'qiut': active = False elif int(age) < 0: print("你不是人,请回你的火星去。") elif int(age) < 3: print("您好,您免费哦!") elif int(age) <= 12: print("您好,收费金额为:10元") elif int(age) > 12: print("您好,收费金额为:15元") #7-6三个出口 : 以另一种方式完成练习7-4或练习7-5, 在程序中采取如下所有做法。 age = '' while True: age = input("您好,请问您的年龄是多少?") if age == 'qiut': print("qiut") break elif int(age) < 0: print("你不是人,请回你的火星去。") elif int(age) < 3: print("您好,您免费哦!") elif int(age) <= 12: print("您好,收费金额为:10元") elif int(age) > 12: print("您好,收费金额为:15元") #7-7无限循环:编写一个没完没了的循环,并运行它(要结束该循环,可按Ctrl+C #,也可关闭显示输出的窗口) while True: print("good") #7-8熟食店:创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字;再 #创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于其中 #的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表 #finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。 sandwich_orders = ['tuna','Cheese','chicken'] finished_sandwiches = [] while sandwich_orders: sandwich = sandwich_orders.pop() print("I made your " + sandwich + "sandwich.") finished_sandwiches.append(sandwich) print("Print out all the sandwiches") #打印出所有三明治。 for sandwich in finished_sandwiches: print(sandwich + "sandwich.") #7-9五香烟熏牛肉(pastrami)卖完了:使用为完成练习7-8而创建的列表sandwich_orders, #并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息, #指出熟食店的五香烟熏牛肉卖完了;再使用一个while循环将列表sandwich_orders中的 #'pastrami'都删除。确认最终的列表finished_sandwiches中不包含'pastrami' sandwich_orders = [ 'tuna', 'pastrami', 'chicken', 'pastrami', 'durian', 'pastrami', 'Cheese' ] finished_sandwiches = [] print("Sorry, we're out of pastrami") while sandwich_orders: sandwich = sandwich_orders.pop() if sandwich == 'pastrami': #比7-8多了这两段 continue print("I made your " + sandwich + " sandwich.") finished_sandwiches.append(sandwich) print("Print out all the sandwiches") #打印出所有三明治。 for sandwich in finished_sandwiches: print(sandwich + " sandwich.") #7-10梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could #visit one place in the world,where would you go?”的提示,并编写一个打印 #调查结果的代码块。 namesCitys = {} verdict = True while verdict: name = input("您好,您叫什么名字?(输入'qiut即结束')") if name == 'qiut': break citys = input("如果你能去到世界上的一个地方,你会去哪里(输入'qiut即结束')") if citys == 'qiut': break namesCitys[name] = citys print(namesCitys)

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第6章习题

#6-1 人:使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应 #包含键first_name、last_name、age和city。将存储在该字典中的每项信息都打印出来。 informations = { 'first_name':'wang', 'last_name':'weizhong', 'city':'Guangyuan' } print(informations) #6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字 #用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。 #打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。 favourite_number = { 'wwz':'8', 'fp':'7', 'lmh':'6', 'aaa':'5', 'bbb':'4' } print(favourite_number) print("www喜欢的数字是:" + str(favourite_number['wwz']) + ".") #6-3 词汇表:Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者 #称为词汇表。 word_implication = { 'print':'显示', 'upper':'全部大写', 'title':'冠字', 'if':'如果', 'input':'显示并输入'} for word in word_implication: print(word + " 的含义是:" + word_implication[word]) #6-4 词汇表2:既然你知道了如何遍历字典,现在请整理你为完成练习6-3而编写的代码, #将其中的一系列print语句替换为一个遍历字典中的键和值的循环。确定该循环正确无 #误后,再在词汇表中添加5个Python术语。当你再次运行这个程序时,这些新术语及其 #含义将自动包含在输出中。 word_implication = { 'print':'显示', 'upper':'全部大写', 'title':'冠字', 'if':'如果', 'input':'显示并输入' } print("键的循环:") for key in word_implication.keys(): print(key) print("值的循环:") for values in word_implication.values(): print(values) #6-5 河流:创建一个字典,在其中存储三条大河流及其流经的国家。其中一个(键—值) #对可能是'nile':'egypt'。 river_country = { 'Nile':'Egypt', 'Mississippi':'USA', 'Danube':'Germany' } for key , values in river_country.items(): print("The " + key.title() + " runs through " + values.title() + ".") for key_river in river_country.keys(): print(key_river.title()) for values_river in river_country.values(): print(values_river.title()) #6-6 调查:在6.3.1节编写的程序favorite_languages.py中执行以下操作。 favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } people_research = ['sarah','phil'] for name in favorite_languages.keys(): if name in people_research: print(name.title() + ",感谢您参加我们的这次关于编程语言的调查!") else: print("亲爱的 " + name.title() + ",我们希望你能参与我们的这次调查!") #6-7 人:在为完成练习6-1而编写的程序中,再创建两个表示人的字典,然后将这三个字典 #都存储在一个名为people的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。 people = { 'name_1':{ 'first_name':'wang', 'last_name':'weizhong', 'city':'guangyuan' }, 'name_2':{ 'first_name':'fan', 'last_name':'peng', 'city':'xuefeng' } } for username , user_inof in people.items(): print("用户:" + username) full_name = user_inof['first_name'] +""+ user_inof['last_name'] city = user_inof['city'] print("全名:" + full_name.title() + " ;住址:" + city.title()) #6-8宠物:创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字 #典中,包含宠物的类型及其主人的名字。 将这些字典存储在一个名为pets的列表中,再遍 #历该列表,并将宠物的所有信息都打印出来。 pets = { 'pumpkin':{'variety':'cat','master':'mwm'}, 'huanhuan':{'variety':'dog','master':'psp'} } for key , value in pets.items(): print(key.title() + "是只" + value['variety'].title() + ",它主人叫做 " + value['master'].title()) #6-9喜欢的地方:创建一个名为favorite_places的字典。在这个字典中,将三个人的名字用作键; #对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练习更有趣些,可让一些朋友指出 #他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。 favorite_places = { 'wps':{'成都','新疆','广州'}, 'tq':{'成都','内江','大邑'}, 'lqz':{'重庆','遂宁','海南'} } for name ,citys in favorite_places.items(): print("Hi," + name.title() +",你喜欢的城市是") for city in citys: print(":" + city) #6-10喜欢的数字:修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数 #字,然后将每个人的名字及其喜欢的数字打印出来。 favourite_number = { 'wwz':{'8','2','9'}, 'fp':{'7','3','1'}, 'lmh':{'6','8','9'}, 'aaa':{'5','2','4'}, 'bbb':{'4','6','0'} } for name , numbers in favourite_number.items(): print(name.title() + ",你喜欢的数字是:") for number in numbers: print(number) #6-11 城市:创建一个名为cities的字典,其中将三个城市名用作键;对于每座城市,都 #创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在 #表示每座城市的字典中,应包含country、population和fact等键。将每座城市的名字 #以及有关它们的信息都打印出来。 cities = { 'chengdu':{'country':'china','population':'20million','fact':'delicious'}, 'london':{'country':'England','population':'30million','fact':'old'}, 'Tokyo':{'country':'Japan','population':'40million','fact':'crowd'} } for city , inof in cities.items(): print(city.title()+ " in " + inof['country'].title() + ".It has a population of " + inof['population'] + "," + "it fact's " + inof['fact'] + ".")

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第5章习题

#5-1 条件测试:编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果 #都打印出来。你编写的代码应类似于下面这样: car = 'subaru' print("Is car == 'subaru'? I predict True.") print(car == 'subaru') print("\nIs car == 'audi'? I predict False.") print(car == 'audi' + "\n") #5-2 更多的条件测试:你并非只能创建10个测试。如果你想尝试做更多的比较,可再编写 #一些测试,并将它们加入到conditional_tests.py中。对于下面列出的各种测试,至少编写 #一个结果为True和False的测试。 #略 #5-3 外星人颜色#1:假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color #的变量,并将其设置为'green'、'yellow'或'red'。 alien_color = 'green' if alien_color == 'green': score = 5 if alien_color == 'red': score = 10 print('你击毁了外星人飞船,获得了 ' + str(score) + '分!') #5-4 外星人颜色#2:像练习5-3那样设置外星人的颜色,并编写一个if-else结构。 alien_color = 'green' if alien_color == 'green': score = 5 else: score = 10 print('你击毁了外星人飞船,获得了 ' + str(score) + '分!') #5-5 外星人颜色#3:将练习5-4中的if-else结构改为if-elif-else结构。 #alien_color = 'green' alien_color = 'yellow' #alien_color = 'red' if alien_color == 'green': score = 5 elif alien_color == 'yellow': score = 10 elif alien_color == 'red': score = 15 else: print('未知') print('你击毁了外星人飞船,获得了 ' + str(score) + '分!') #5-6人生的不同阶段:设置变量age的值,再编写一个if-elif-else结构,根据age #的值判断处于人生的哪个阶段。 age = 5 if age < 2: message = '婴儿' elif age < 4: message = '正在学步' elif age < 13: message = '儿童' elif age < 20: message = '青年' elif age < 65: message = '成年' else: message = '老年' print("他现在是" + message + "了。") #5-7 喜欢的水果:创建一个列表,其中包含你喜欢的水果,再编写一系列独立的if语 #句,检查列表中是否包含特定的水果。 favorite_fruits = ['apple','litchi','watermelon'] watermelon = 'watermelon' if 'bananas' in favorite_fruits: print("You really like bananas!") if 'orange' in favorite_fruits: print("You really like orange!") if 'pear' in favorite_fruits: print("You really like pear!") if 'apple' in favorite_fruits: print("You really like apple!") if 'watermelon' in favorite_fruits: print("You really like watermelon!") #5-8 以特殊方式跟管理员打招呼:创建一个至少包含5个用户名的列表,且其中一个用 #户名为'admin'。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍 #历用户名列表,并向每位用户打印一条问候消息。 names = ['zi52','wwwww','zzia','admin','ookkl'] for name in names: if name =='admin': print("您好," + name.title() + ",您想查看今天的数据吗?") else: print("您好," + name.title() + ",欢迎登陆!") #5-9 处理没有用户的情形:在为完成练习5-8编写的程序中,添加一条if语句,检查用 #户名列表是否为空。 names = [] if names : for name in names: if name =='admin': print("您好," + name.title() + ",您想查看今天的数据吗?") else: print("您好," + name.title() + ",欢迎登陆!") else: print("我们需要一些用户") #5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无 #二的方式。 current_users = ['Zi52','wwwww','Zzia','admin','ookkl'] new_users = ['jjjll','zi52','kkkij','zzia','oooxxx'] for new in new_users: if new.lower() in [current_user.lower() for current_user in current_users]: print(new + "此用户名已经被占用,请重新输入!") else: print(new + "此用户名可以使用。") #5-11 序数:序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。 #在一个列表中存储数字1~9。 num = list(range(1,10)) for nu in num: if nu == 1: print(str(nu) + 'st') elif nu == 2: print(str(nu) + 'nt') elif nu == 3: print(str(nu) + 'rt') else: print(str(nu) + 'tt')

优秀的个人博客,低调大师

Golang 入门系列(五)GO语言中的面向对象

前面讲了很多Go 语言的基础知识,包括go环境的安装,go语言的语法等,感兴趣的朋友可以先看看之前的文章。https://www.cnblogs.com/zhangweizhong/category/1275863.html。 今天GO语言中的面向对象。 GO语言中的面向对象 其实GO并不是一个纯面向对象编程语言。它没有提供类(class)这个关键字,只提供了结构体(struct)类型。 java或者C# 里面,结构体(struct)是不能有成员函数的。然而,Go语言中的结构体(struct)可以有"成员函数"。方法可以被添加到结构体中,类似于一个类的实现。 我个人觉得Go 语言在的面向对象,其实更简单,也更容易理解。 学过java或C# 的人应该都知道,面向对象的三个基本特征:封装、继承和多态。他们的定义我这里就不细说了。下面,就直接看看 go 语言下的面向对象是怎样实现的吧。 1. 封装特性 Golang区分公有属性和私有属性的机制就是方法或属性是否首字母大写,如果首字母大写的方法就是公有的,如果首字母小写的话就是私有的。 package main import "fmt" type Person struct { name string } func (person *Person) setName(name string) { person.name = name } func (person *Person) GetInfo() { fmt.Println(person.name) } func main() { p := Person{"zhangsan"} p.setName("lisi") p.GetInfo() } 2. 继承特性 GO语言的继承方式采用的是匿名组合的方式:Woman 结构体中包含匿名字段Person,那么Person中的属性也就属于Woman对象。 package main import "fmt" type Person struct { name string } type Woman struct { Person sex string } func main() { woman := Woman{Person{"wangwu"}, "女"} fmt.Println(woman.name) fmt.Println(woman.sex) } 3. 多态特性 package main import "fmt" type Eater interface { Eat() } type Man struct { } type Woman struct { } func (man *Man) Eat() { fmt.Println("Man Eat") } func (woman *Woman) Eat() { fmt.Println("Woman Eat") } func main() { var e Eater woman := Woman{} man := Man{} e = &woman e.Eat() e = &man e.Eat() } 最后 以上,就把Go语言如何实现面向对象的简单介绍了一下,其实跟java和C# 等也都差不多,大家可以比较着来看。总结的来说就是:Go没有类,而是松耦合的类型、方法对接口的实现。 作者:章为忠 出处:http://www.fpeach.com/ 本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以微信:18618243664联系我,非常感谢。 扫下面的二维码关注我的微信公众号。

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第4章习题

#4-1比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中, #再使用for循环将每种比萨的名称都打印出来。 pizza_toppings =['Durian','Bacon','Shrimp'] for toppings in pizza_toppings: print("I like " + toppings.title() + " pizza.") print("I really love pizza!") #4-2 动物: 想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中, #再使用for循环将每种动物的名称都打印出来。 zoologys = ['cat','dog','pig'] for zoology in zoologys: print("A" + zoology.title() + "would make a great pet.") print("Any ofthese animals would make a great pet!") #4-3 数到20:使用一个for循环打印数字1~20(含)。 for number in range(1,21): print(number) #4-4 一百万:创建一个列表,其中包含数字1~1 000 000,再使用一个for循环 #将这些数字打印出来(如果输出的时间太长,按Ctrl + C停止输出,或关闭输出窗口)。 millions = list(range(1,1000001)) for million in millions: print(million) #4-5 计算1~1000000的总和:创建一个列表,其中包含数字1~1 000 000,再使用min()和 #max()核实该列表确实是从1开始,到1000000结束的。另外,对这个列表调用函数sum(), #看看Python将一百万个数字相加需要多长时间。 millions = list(range(1,1000001)) print(min(millions)) print(max(millions)) print(sum(millions)) #4-6 奇数:通过给函数range()指定第三个参数来创建一个列表,其中包含1~20的奇数; #再使用一个for循环将这些数字都打印出来。 odd_number = list(range(1,20,2)) for number in odd_number: print(number) #4-7 3的倍数:创建一个列表,其中包含3~30内能被3整除的数字; #再使用一个for循环将这个列表中的数字都打印出来。 triples = list(range(3,31,3)) for triple in triples: print(triple) #4-8 立方:将同一个数字乘三次称为立方。例如,在Python中,2的立方用2**3表示。请创建 #一个列表,其中包含前10个整数(即1~10)的立方,再使用一个for循环将这些立方数都打印出来。 cube = [] for num in range(1,11): cube.append(num**3) print(cube) #4-9 立方解析 : 使用列表解析生成一个列表, 其中包含前10个整数的立方。 cubes = [num**3 for num in range(1,11)] print(cubes) #4-10 切片:选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。 zoologys = ['cat','dog','pig','cow','panda'] print("The first three items in the list are:") print(zoologys[0:3]) print("Three items from the middle of the list are:") print(zoologys[1:4]) print("The last three items in the list are:") print(zoologys[-3:]) #4-11 你的比萨和我的比萨:在你为完成练习4-1而编写的程序中,创建比萨列表的副本, #并将其存储到变量friend_pizzas中,再完成如下任务。,'lobster','mushroom' pizza_toppings =['Durian','Bacon','Shrimp'] friend_pizzas = pizza_toppings[:] pizza_toppings.append('mushroom') friend_pizzas.append('lobster') print("My favorite pizzas are:") print(pizza_toppings) print("My friend's favorite pizzas are:") print(friend_pizzas) #4-12 使用多个循环:在本节中,为节省篇幅,程序foods.py的每个版本都没有使用for循环 #来打印列表。请选择一个版本的foods.py,在其中编写两个for循环,将各个食品列表都 #打印出来。 my_foods = ['pizza', 'falafel', 'carrot cake'] for my_food in my_foods: print(my_food) #4-13 自助餐:有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品, #并将其存储在一个元组中。 buffet = ('beef','fish','chicken','salad','dessert') for food in buffet: print(food) buffet[2] = 'lobster' buffet = ('beef','salmon','MuttonShashlik','salad','dessert') for food_2 in buffet: print(food_2)

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第3章习题

#3-1 姓名: 将一些朋友的姓名存储在一个列表中, 并将其命名为names。 #依次访问该列表中的每个元素, 从而将每个朋友的姓名都打印出来。 names = ['mengxiang','lindan','zhaodianyan','fanpeng'] for name in names: print(name) #3-2 问候语: 继续使用练习3-1中的列表,但不打印每个朋友的姓名, #而为每人打印一条消息。 每条消息都包含相同的问候语, 但抬头为相应朋友的姓名。 names = ['mengxiang','lindan','zhaodianyan','fanpeng'] for name in names: print(name) print("Hello! Have you studied today?") #3-3自己的列表: 想想你喜欢的通勤方式, 如骑摩托车或开汽车, 并创建一个包含多种通勤 #方 式的列表。 根据该列表打印一系列有关这些通勤方式的宣言, 如“Iwould like toowna #Honda motorcycle”。 commutings = ['bike','bus','car'] for commuting in commutings: print("I travel by" + commuting + "!") #3-4嘉宾名单: 如果你可以邀请任何人一起共进晚餐(无论是在世的还是故去的),你会邀 #请哪些人? 请创建一个列表,其中包含至少3个你想邀请的人;然后,使用这个列表打印消 #息,邀请这些人来与你共进晚餐。 names = ['wwz','fp','tq'] for name in names: print(name.title() + ",中午咱们去搓一顿,我请客!") #3-5 修改嘉宾名单 : 你刚得知有位嘉宾无法赴约, 因此需要另外邀请一位嘉宾。 names = ['wwz','fp','tq'] pop_names = names.pop(2) print(pop_names.title() + "不能来参加聚会了。") names.insert(2,'wg') for name in names: print(name.title() + ",中午咱们去搓一顿,我请客!") #3-6 添加嘉宾:你刚找到了一个更大的餐桌,可容纳更多的嘉宾。请想想你还想邀请哪三 #位嘉宾。 names = ['wwz','fp','tq'] names.insert(0,'wm') names.insert(2,'zdy') names.append('jg') for name in names: print(name.title() + ",中午咱们去搓一顿,我请客!") #3-7缩减名单:你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。 names = ['wwz','fp','tq'] names.insert(0,'wm') names.insert(2,'zdy') names.append('jg') print("我曹,对不住了兄弟!今只能请两个人搓了,地小装不下。") for x in range(0,4): pop_namesr = names.pop(-1) print(pop_namesr + ",兄弟我这里给你赔不是,下次单独请你!") for name in names: print(name.title() + ",中午咱们去搓一顿,我请客!") del names[0] del names[0] print(names) #3-8 放眼世界:想出至少5个你渴望去旅游的地方。 countrys = ['Netherlands','Switzerland','Germany','England','Greece'] print(countrys) print(sorted(countrys)) print(countrys) print(sorted(countrys,reverse=True)) print(countrys) countrys.reverse() print(countrys) countrys.reverse() print(countrys) countrys.sort() print(countrys) countrys.sort(reverse=True) print(countrys) #3-9 晚餐嘉宾:在完成练习3-4~练习3-7时编写的程序之一中, #使用len()打印一条消息,指出你邀请了多少位嘉宾来与你共进晚餐。 names = ['wwz','fp','tq'] print(len(names)) #3-10 尝试使用各个函数:想想可存储到列表中的东西,如山岳、河流、国家、城市、语言或 #你喜欢的任何东西。编写一个程序,在其中创建一个包含这些元素的列表,然后,对于本章 #介绍的每个函数,都至少使用一次来处理这个列表。 #略 #3-11有意引发错误:如果你还没有在程序中遇到过索引错误,就尝试引发一个这种错误。 #在你的一个程序中,修改其中的索引,以引发索引错误。关闭程序前,务必消除这个错误。 lens = ['a','b','c','d'] print(lens[4])

优秀的个人博客,低调大师

《Python编程:从入门到实践》 第2章习题

#2-1 简单消息:将一条消息储存到变量中,再将其打印出来。 message = 'Hi, I am a happy Coder' print(message) #2-2 多条简单消息: 将一条消息存储到变量中, 将其打印出来; 再将变量的值修改为一条新消息, 并将其打印出来。 message = 'I am coming' print(message) #2-3个性化消息: 将用户的姓名存到一个变量中, 并向该用户显示一条消息。 显示的消息 应非常简单, 如“ Hello Eric, would you like to learn some Python today?” 。 name = 'WWZ' print("Hello " + name.title() + " would you like to learn some Python today?" ) #2-4 调整名字的大小写: 将一个人名存储到一个变量中, 再以小写、 大写和首字母大写的 方式显示这个人名。 name = 'WWZ' print(name.lower()) print(name.upper()) print(name.title()) #2-5 名言: 找一句你钦佩的名人说的名言, 将这个名人的姓名和他的名言打印出来。 输出应类似于下面这样(包括引号) : print("孔子曾说过,“学而不思则罔,思而不学则殆。”") #2-6 名言2: 重复练习2-5, 但将名人的姓名存储在变量famous_person中, 再创建要显示的消息, 并将其存储在变量message中, 然后打印这条消息。 famous_person = "孔子" message = "“学而不思则罔,思而不学则殆。”" print(famous_person + "曾说过," + message) #2-7 剔除人名中的空白: 存储一个人名,并在其开头和末尾都包含一些空白字符。 务必至少使用字符组合"\t"和"\n"各一次。 name = " \t WWZ " name2 = " \n WWZ " print(name.lstrip()) print(name.rstrip()) print(name.strip()) print(name2.lstrip()) print(name2.rstrip()) print(name2.strip()) #2-8 数字8: 编写4个表达式, 它们分别使用加法、 减法、 乘法和除法运算, 但结果都是数字 8。 为使用print语句来显示结果, 务必将这些表达式用括号括起来, 也就是说, 你应该 编写4行类似于下面的代码: print(2+6) print(10-2) print(2*4) print(16/2) #2-9 最喜欢的数字: 将你最喜欢的数字存储在一个变量中, 再使用这个变量创建一条消息,指出你最喜欢的数字, 然后将这条消息打印出来。 number = 1 message = "My favorite number is," print(message + str(number)) #2-10添加注释: 选择你编写的两个程序, 在每个程序中都至少添加一条注释。 如果程序太简单, 实在没有什么需要说明的, 就在程序文件开头加上你的姓名和当前日期, 再用一句话阐述程序的功能。 number = 1 #喜欢的数字 message = "My favorite number is," #阐述消息 print(message + str(number)) #2-11 Python之禅: 在Python终端会话中执行命令import this, 并粗略地浏览一下其他的指导原则。 import this

优秀的个人博客,低调大师

带你入门Python爬虫,8个常用爬虫技巧盘点

python作为一门高级编程语言,它的定位是优雅、明确和简单。 我学用python差不多一年时间了, 用得最多的还是各类爬虫脚本, 写过抓代理本机验证的脚本、写过论坛中自动登录自动发贴的脚本 写过自动收邮件的脚本、写过简单的验证码识别的脚本。 这些脚本有一个共性,都是和web相关的, 总要用到获取链接的一些方法,故累积了不少爬虫抓站的经验, 在此总结一下,那么以后做东西也就不用重复劳动了。 如果你在学习Python的过程中遇见了很多疑问和难题,可以加-q-u-n227 -435-450里面有软件视频资料免费领取 1、基本抓取网页 get方法 post方法 2.使用代理服务器 这在某些情况下比较有用, 比如IP被封了,或者比如IP访问的次数受到限制等等。 3.Cookies处理 是的没错,如果想同时用代理和cookie, 那就加入proxy_support然后operner改为 ,如下: 4.伪装成浏览器访问 某些网站反感爬虫的到访,于是对爬虫一律拒绝请求。 这时候我们需要伪装成浏览器, 这可以通过修改http包中的header来实现: 5、页面解析 对于页面解析最强大的当然是正则表达式, 这个对于不同网站不同的使用者都不一样,就不用过多的说明。 其次就是解析库了,常用的有两个lxml和BeautifulSoup。 对于这两个库,我的评价是, 都是HTML/XML的处理库,Beautifulsoup纯python实现,效率低, 但是功能实用,比如能用通过结果搜索获得某个HTML节点的源码; lxmlC语言编码,高效,支持Xpath。 6.验证码的处理 碰到验证码咋办? 这里分两种情况处理: google那种验证码,没办法。 简单的验证码:字符个数有限,只使用了简单的平移或旋转加噪音而没有扭曲的, 这种还是有可能可以处理的,一般思路是旋转的转回来,噪音去掉, 然后划分单个字符,划分好了以后再通过特征提取的方法(例如PCA)降维并生成特征库, 然后把验证码和特征库进行比较。 这个比较复杂,这里就不展开了, 具体做法请弄本相关教科书好好研究一下。 7. gzip/deflate支持 现在的网页普遍支持gzip压缩,这往往可以解决大量传输时间, 以VeryCD的主页为例,未压缩版本247K,压缩了以后45K,为原来的1/5。 这就意味着抓取速度会快5倍。 然而python的urllib/urllib2默认都不支持压缩 要返回压缩格式,必须在request的header里面写明’accept-encoding’, 然后读取response后更要检查header查看是否有’content-encoding’一项来判断是否需要解码,很繁琐琐碎。 如何让urllib2自动支持gzip, defalte呢? 其实可以继承BaseHanlder类, 然后build_opener的方式来处理: 8、多线程并发抓取 单线程太慢的话,就需要多线程了, 这里给个简单的线程池模板 这个程序只是简单地打印了1-10, 但是可以看出是并发的。 虽然说Python的多线程很鸡肋 但是对于爬虫这种网络频繁型, 还是能一定程度提高效率的。 9. 总结 阅读Python编写的代码感觉像在阅读英语一样,这让使用者可以专注于解决问题而不是去搞明白语言本身。 Python虽然是基于C语言编写,但是摒弃了C中复杂的指针,使其变得简明易学。 并且作为开源软件,Python允许对代码进行阅读,拷贝甚至改进。 这些性能成就了Python的高效率,有“人生苦短,我用Python”之说,是一种十分精彩又强大的语言。 总而言之,开始学Python一定要注意这4点: 1.代码规范,这本身就是一个非常好的习惯,如果开始不养好好的代码规划,以后会很痛苦。 2.多动手,少看书,很多人学Python就一味的看书,这不是学数学物理,你看例题可能就会了,学习Python主要是学习编程思想。 3.勤练习,学完新的知识点,一定要记得如何去应用,不然学完就会忘,学我们这行主要都是实际操作。 4.学习要有效率,如果自己都觉得效率非常低,那就停不停,找一下原因,去问问过来人这是为什么。

优秀的个人博客,低调大师

一文带你入门图论和网络分析

简介 俗话说一图胜千言。但是“图”(Graph)说的远不止于此。以图形式呈现的数据可视化能帮助我们获得见解,并基于它们做出更好的数据驱动型决策。 但要真正理解图是什么以及为什么使用它们,我们需要理解一个称为图论(Graph Theory)的概念。理解它可以使我们成为更好的程序员。 如果你曾经尝试理解这个概念,应该会遇到大量的公式和干涩的理论。这便是为什么我们要写这篇博文的原因。我们先解释概念,然后提供实例,以便你可以跟随并弄明白它的执行方式。这是一篇详细的文章,因为我们认为提供概念的正确解释要比简洁的定义更受欢迎。 在本文中,我们将了解图是什么,它们的应用以及一些历史背景。我们还将介绍一些图论概念,然后使用进行案例研究以巩固理解。 准备好了吗?我们开始吧。 目录 图及其应用图论的历史、为何使用图论必备术语图论概念熟悉Python中的图数据分析案

优秀的个人博客,低调大师

C++入门:与Python对比第一弹

因为下学期会学c++面向对象编程,还有接下来的项目中可能会用到c++,所以决定先提前学习下,顺便与python做个比对,还是有许多相似之处的。=v= 下面是两个简单例子对比。 1,for循环 C++ #include <iostream> using namespace std; int main() { int a = 5; for (a; a < 10; a += 1) { cout << "a的值为:" << a << endl; } system("PAUSE"); return 0; } Python for a in range(5, 10): if a < 10: print('a的值为:', a) a += 1 else: break 输出都为: a的值为: 5 a的值为: 6 a的值为: 7 a的值为: 8 a的值为: 9 2,while循环 C++ #include <iostream> using namespace std; int main () { int a = 5; while( a < 10 ) { cout << "a 的值:" << a << endl; a++; } system("PAUSE"); return 0; } Python a = 5 while a < 10: print('a的值为:', a) a += 1 输出都为: a的值为: 5 a的值为: 6 a的值为: 7 a的值为: 8 a的值为: 9 额,那个,我想说:人生苦短,我学python!当然C++在开发驱动程序,系统服务,高效的网络通信程序(比如大型网游)。C++的执行效率是最高的。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册