《笨方法学Python》加分题 40 - 42

Posted 阿加西的python之旅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《笨方法学Python》加分题 40 - 42相关的知识,希望对你有一定的参考价值。

习题 40:模块、类和对象

字典和模块使用方式有点类似,只是语法不同([键]和.键):
Python里一个通用模式:1)类似“键=值”风格的容器;2)通过“键”的名称获取其中的值


模块是包含函数和变量的 Python 文件,可以导入这个文件,可以使用 "." 操作符访问模块中的函数和变量。

模块还可以用一种方法去理解:可以把它们当做一种特殊的字典,通过它们可以存储一些 Python 代码,可以通过 "." 操作符访问这些代码。Python 还有一种另外一种代码结构用来实现类似的目的,那就是类,通过类,你可以把一组函数和数据放到一个容器中,从而用 "." 操作符访问类中的函数和变量。

 

使用类而非模块的原因:其重复创建很多出来(类可以多次实例化),这些实例之间也不会相互干涉;而模块一次导入之后,整个程序中只有这么一份内容

对象相当于迷你导入

 

 

 

现在有三种方法可以从某个东西里获取东西:

# dict sytle
mystuff[\'apples\']
 
# module style            调用模块
mystuff.apples()        # 访问模块的函数
mystuff.tangerine       # 访问模块的变量
 
# class style
thing = MyStuff()         调用类
thing.apples()          # 访问类的函数
thing.tangerine         # 访问类的变量

 

 

class Song:
    
    def __init__(self, lyrics):
        self.lyrics = lyrics
        
    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)
            
happy_bday = Song(["Happy birthday to you",            # 调用类
                   "I don\'t want to get sued",
                   "So I\'ll stop right there"])
 
bulls_on_parade = Song(["There rally around the family",
                        "With pockets full of shells"])
                        
happy_bday.sing_me_a_song()
 
bulls_on_parade.sing_me_a_song()

 

创建 __init__ 或者别的类函数时需要多加一个 self 变量。

 

 

习题 41:学习面向对象术语

 1 import random
 2 from urllib.request import urlopen
 3 import sys
 4 
 5 WORD_URL = "http://learncodethehardway.org/words.txt"
 6 WORDS = []
 7 
 8 PHRASES = {
 9     "class %%%(%%%):":
10       "Make a class named %%% that is-a %%%.",
11     "class %%%(object):\\n\\tdef __init__(self, ***)" :
12       "class %%% has-a __init__ that takes self and *** params.",
13     "class %%%(object):\\n\\tdef ***(self, @@@)" :    
14       "class %%% has-a function *** that takes self and @@@ params.",
15     "*** = %%%()":
16       "Set *** to an instance of class %%%.",
17     "***.***(@@@)":
18       "From *** get the *** function, call it with params self, @@@.",
19     "***.*** = \'***\'":
20       "From *** get the *** attribute and set it to \'***\'."
21 }
22 
23 # do they want to drill phrases first
24 if len(sys.argv) == 2 and sys.argv[1] == "english":
25     PHRASE_FIRST = True
26 else:
27     PHRASE_FIRST = False
28 
29 # load up the words from the website
30 for word in urlopen(WORD_URL).readlines():
31     WORDS.append(str(word.strip(), encoding = "utf-8"))
32 
33 def convert(snippet, phrase):
34     class_names = [w.capitalize() for w in
35                    random.sample(WORDS, snippet.count("%%%"))]
36     other_names = random.sample(WORDS, snippet.count("%%%"))  
37     results = []
38     param_names = []
39 
40     for i in range(0, snippet.count("@@@")):
41         param_count = random.randint(1,3)
42         param_names.append(\',\'.join(
43             random.sample(WORDS, param_count)))
44 
45     for sentence in snippet, phrase:
46         result = sentence[:]
47 
48         #fake class names
49         for word in class_names:
50             result = result.replace("%%%", word, 1)
51         #fake other names
52         for word in other_names:
53             result = result.replace("***", word, 1)
54         #fake parameter names
55         for word in param_names:
56             result = result.replace("@@@", word, 1)
57 
58         results.append(result)
59     return results
60 
61 # keep going until they hit CTRL-D
62 try:
63     while True:
64         snippets = list(PHRASES.keys())
65         random.shuffle(snippets)
66 
67         for snippet in snippets:
68             phrase = PHRASES[snippet]
69             question, answer = convert(snippet, phrase)
70             if PHRASE_FIRST:
71                 question, answer = answer, question
72 
73             print(question)
74 
75             input("> ")
76             print(f"ANSWER: {answer}\\n\\n")
77 
78 except EOFError:
79     print("\\nBye")
80 
81     result = sentence[:]
82     print(result)

 

习题 42:对象、类及从属关系

 1 ## Animal is-a object (yes, sort of confusing) look at the extra credit
 2 class Animal(object):
 3     pass
 4 
 5 ## Dog is-a Animal
 6 class Dog(Animal):
 7 
 8     def __init__(self, name):
 9         ## ??
10         self.name = name
11 
12 ## Cat is-a Animal
13 class Cat(Animal):
14 
15     def __init__(self, name):
16         ## ??
17         self.name = name
18     
19 ## Person is-a Animal
20 class Person(Animal):
21 
22     def __init__(self, name):
23         ## ??
24         self.name = name
25         
26         ## Person has-a pet of some kind
27         self.pet = None
28 
29 ## Employee is-a Person
30 class Employee(Person):
31 
32     def __init__(self, name, salary):
33         ## ?? hmm what is this strange magic?
34         super(Employee, self).__init__(name)
35         ## ??
36         self.salary =salary
37 
38 ## Fish is-a object
39 class Fish(object):
40     pass
41 
42 ## Salmon is-a Fish
43 class Salmon(Fish):
44     pass
45 
46 ## Halibut is-a Fish
47 class Halibut(Fish):
48     pass
49 
50 ## rover is-a dog
51 rover = Dog("Rover")
52 
53 ## satan is-a Cat
54 satan = Cat("Satan")
55 
56 ## mary is-a Person
57 mary = Person("Mary")
58 
59 ## mary has-a pet, satan is-a Cat
60 mary.pet = satan
61 
62 ## ??
63 frank = Employee("Frank", 12000)
64 
65 ## ??
66 frank.pet =rover
67 
68 ## ??
69 flipper =Fish()
70 
71 ## ??
72 crouse = Salmon()
73 
74 ## ??
75 harry = Halibut()

 

 

 

习题41涉及到的函数

 

https://www.runoob.com/python/python-func-str.html

https://www.runoob.com/python3/python3-string-strip.html

https://www.runoob.com/python3/python3-func-number-random.html

https://www.runoob.com/python3/python3-random-number.html

https://www.runoob.com/python/python-exercise-example94.html

https://www.runoob.com/python3/python3-string-capitalize.html

https://www.runoob.com/python3/python3-att-dictionary-keys.html

https://www.runoob.com/python3/python3-string-count.html

https://www.runoob.com/python3/python-copy-list.html

https://www.runoob.com/python3/python3-string-replace.html

https://www.runoob.com/python3/python3-func-number-shuffle.html

以上是关于《笨方法学Python》加分题 40 - 42的主要内容,如果未能解决你的问题,请参考以下文章

《笨方法学Python》加分题35

《笨方法学Python》加分题28

笨办法学python 习题42 加分练习

笨办法学python pdf下载

笨方法学Python——习题40

笨办法学Python(三十)