笨方法学python40-42

习题 40

概要:

# 模块、类和对象
'''
python是面向对象编程语言、
通过class(类)的结构,用特殊的方式构造软件
使用类可以加强程序的一致性
'''
'''
模块和字典差不多,这是将一个东西映射到另外一个东西的方式,这意味着,
如果你有一个字典,有’apple‘的键(key),而你从key取值value需要:
'''
mystuff={'apple':'I AM APPLES!'}
print(mystuff['apple'])
'''
注意:从Y取X的概念,再看module,
- module包含了函数和变量的python文件
- 可以导入这个文件
- 使用.操作访问module的函数和变量
'''
# this goes in mystuff.py
def apple():
    print("I AM APPLES!")

import mystuff
mystuff.apple()
'''还可以将tangerine的变量放到module里'''
def apple():
    print("I AM APPLES!")
#this is just a variable
tangerine="Living reflections of a dream"
'''同样,还是可以访问这个变量'''
import mystuff

mystuff.apple()
print(mystuff.tangerine)
'''回到字典的概念,module与字典的使用方式相似,只不过语法不同'''
mystuff['apple']#get apple from dict
mystuff.apple()#get apple from the module
mystuff.tangerine#same things,it's just a variable
'''python的常用模式
- 键=值
- 通过键的名称获取其中的值
对于字典来说,key是一个字符串,获得值的语法是[key]
对于模块来说,key是函数或者变量的名称,而语法是“.key”
'''
class Mystuff(object):
    def_init_(self):
        self.tangerine="And now a thousand years between"
    def apple(self):
        print("I AM CLASSY APPLES!")
'''
对象(object)与import差不多,实例化(instantiate)
也就是,创建的意思
将类实例化,就会得到对象,像调用函数一样调用类
'''

thing=Mystuff()#实例化,与调用函数很相似
thing.apple()
print(thing.tangerine)
'''
- python查找Mystuff()就会知道,Mystuff()是你定义的类
- python创建了一个空对象,里面包含了你在该类用def指定的所有函数
- python会去检查你是不是在里面创建了_init_函数,如果有创建,就会调用函数,从而对你新创建的空对象实现了初始化
- 在Mystuff的_int_函数里,有一个多余的函数self,这就是python为你创建的空对象,而你可以对self进行module,dict等操作,为self设置变量
- python将这个新建的对象赋给thing变量,以供后面使用
'''
'''
- 类就像一种蓝图或者一种预定的东西,通过类创建新的迷你module
- 实例化的过程相当于你创建了一个迷你模块,而且同时导入了它;实例化:从类创建一个对象
- 结果创建的迷你模块就是一个对象,可以将它赋给一个变量,以供后面操作
'''
# dict style
mystuff['apple']
#moudle stuyle
mystuff.apple()
print(mystuff.tangerine)
#class style
thing=Mystuff
thing.apples()
print(thing.tangrine)

代码如下:

'''第一个类的例子'''
class Song(object):
    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(["They rally around the family",
                      "With pockets full of shells"])

happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()


'''为什么创建__init__或者别的类函数时需要多加一个self变量?
如果不加self,cheese='Frank'的代码没有歧义,既可能是实例的cheese属性,也可能是一个叫做cheese的局部变量
有了self.cheese='Frank'就清楚的知道这指的是实例的属性self.cheese
'''

结果输出:

Happy birthday to you
I don't want to get sued
So,I'll stop right there
They rally around the family
With pockets full of shells

进程已结束,退出代码0

习题41

代码如下:

'''
类(class):告诉python创建新类型的东西
对象(object):两个意思,即最基本的东西,或者某样东西的实例
实例(instance):python创建一个类时得到的东西
def:这是在类里定义函数的方法
self:在类的函数中,self指被访问的对象或实例的一个变量
继承(inheritance):指一个类可以继承另一个类的特性,与父子关系类似
组合(composition):指一个类可以将识别的类作为它的部件构建起来,有点像车子和车轮的关系
属性(attribute):类的属性,来自于组合,而且通常是一个变量
是什么(is-a):用来描述继承关系,,如Salmon is_a Fish
有什么(has-a):用来描述某个东西是由另外一个东西组成的,或者某个东西有某个特征,,如Salomon 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
'''
import random
from urllib.request import urlopen
import sys

WORD_URL="http://learncodethehardway.org/words.txt"
WORDS=[]

PHRASES= {
    "class %%%(%%%)":
        "make a class named % % % that is-a %%%.",
    "class %%%(object):\n\t def __init__(self,***)":
        'class %%% has-a __init__ that takes self and *** params.',
    'class %%% (object):\n\t def ***(self,@@@)':
        "class % % % has_a function *** that takes self and *** params.",
    "***=%%%()":
        "set *** to an instance of class %%%.",
    "***.***(@@@)":
        "from *** get the *** function, call it with params self,@@@.",
    "***.***='***'":
        "from *** get the *** attribute and set it to '***'."
}
#do they want to drill phrases first
if len(sys.argv)==2 and sys.argv[1]=="english":
    PHRASES_FIRST=True
else:
    PHRASES_FIRST=False
#load up the words from the website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(),encoding="utf-8"))
def convert(snippet,phrase):
    class_names=[w.capitalize()for w in
                 random.sample(WORDS,snippet.count("%%%"))]
    other_names=random.sample(WORDS,snippet.count("%%%"))
    results=[]
    param_names=[]
    for i in range(0,snippet.count("@@@")):
        param_count=random.randint(1,3)
        param_names.append(','.join(
            random.sample(WORDS,param_count)))
        for sentence in snippet,phrase:
            result=sentence[:]
            #fake class names
            for word in class_names:
                results=result.resplace("%%%",word,1)
            #fake other names
            for word in other_names:
                results=result.resplace("***",word,1)
            #fake parameter lists
            for word in param_names:
                results=result.resplace("@@@",word,1)
            results.append(result)
        return results
    #Keep going until they hit CTRL-D
    try:
        while True:
            snippets=list(PHRASES.keys())
            random.shuffle(snippets)

            for snippet in snippets:
                phrase=PHRASES[snippets]
                question,answer=convert(snippet,phrase)
                if PHRASES_FIRST:
                    question,answer=answer,question
                print(question)
                input(">")
                print(f"ANSWER:{answer}\n\n")
    except EOFError:
        print("\nBey")
'''
result=sentence[:]是什么意思?
python复制列表的方法,你正在使用“列表切片(list slicing)”语法[:]对列表中的所有元素进行切片操作
'''

习题42

代码如下:

#对象、类和从属关系
'''
is-a(是什么)两者以类的关系相互关联
has-a(有什么)两者无共同点,仅是互为参照
'''
## Animal is-a object (yes,sort of confusing) look at the extra credit
class Animal(object):
    pass
class Dog(Animal):
    def __init__(self,name):
        self.name=name

class Cat(Animal):
    def __init__(self,name):
        self.name=name

class Person(object):
    def __init__(self,name):
        self.name=name
        ##Person has-a pet of some kind
        self.pet=None

class Employee(Person):
    def __init__(self,name,salary):
#??hmm,what is this strange magic?
        super(Employee,self).__init__(name)
        self.salary=salary

class Fish(object):
    pass
class Salmon(Fish):
    pass
class Halibut(Fish):
    pass
#rover is-a Dog
rover=Dog("rover")
satan=Cat("Satan")
mary=Person("Mary")
mary.pet=satan
frank=Employee("Frank",120000)
frank.pet=rover
flipper=Fish()
crouse=Salmon()
harry=Halibut()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值