Python语言的面相对象编程方式初步学习
词语练习
通过卡片记忆这些词语,单独的词语通常没什么意义,不过我还是要先知道它们的存在。 短语练习
上面那些x,y,m,q等等都是可以变的。 一个阅读测试 import random from urllib import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class ###(###):": "Make a class named ### that is-a ###.","class ###(object):ntdef __init__(self,***)" : "class ### has-a __init__ that takes self and *** parameters.","class ###(object):ntdef ***(self,@@@)": "class ### has-a function named *** that takes self and @@@ parameters.","*** = ###()" : "Set *** to an instance of class ###.","***.***(@@@)" : "From *** get the *** function,and call it with parameters self,@@@.","***.*** = '***'": "From *** get the *** attribute and set it to '***'." } PHRASE_FIRST = False if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True for word in urlopen(WORD_URL).readlines(): WORDS.append(word.strip()) 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: result = result.replace("###",word,1) # fake other names for word in other_names: result = result.replace("***",1) # fake parameter lists for word in param_names: result = result.replace("@@@",1) results.append(result) return results try: while True: snippets = PHRASES.keys() random.shuffle(snippets) for snippet in snippets: phrase = PHRASES[snippet] question,answer = convert(snippet,phrase) if PHRASE_FIRST: question,answer = answer,question print question raw_input("> ") print "ANSWER: %snn" % answer except EOFError: print "nBye"
root@he-desktop:~/mystuff# python oop_test.py class Deer(object): def __init__(self,connection) > ANSWER: class Deer has-a __init__ that takes self and connection parameters. class Cause(Agreement): > ANSWER: Make a class named Cause that is-a Agreement. animal.driving(arch) > ANSWER: From animal get the driving function,arch. cat = Aftermath() > ANSWER: Set cat to an instance of class Aftermath. cork.card = 'attempt' >
如果我要写一个类似mystuff的类,就像这样: class mystuff(object): def __int__(self): self.tangerine = "Hello" def apple(self): print "apple" 和模块比有点复杂,不过你可以认为它就是一个迷你模块。让人疑惑的是__init__()函数和self.tangerine设置tangerine变量的值。 这里是用类替代模块的原因:你可以在一个程序中使用同一个类很多次,它们不相互影响,但是一个程序中只能导入一个模块。 理解这些之前,你必须理解什么是对象。 对象就像迷你的导入 使用类的方法类似调用函数,像这样: thing = mystuff() thing.apple() print thing.tangerine 第一步是实例化,然后调用它的函数,我们通过上面的代码分析一下python是怎么按照顺序执行的:
这就是我们为什么像调用函数一样导入一个类。 记住,我给出的不是一个非常准确类的工作方法,仅仅是为了你能通过模块而更好的理解类。事实是,类和对象和模块不是一个东西,老实说的话,就像下面这样:
从东西中取出东西 # 字典 mystuff['apple'] # 模块 mystuff.apple() print mystuff.tangerine # 类 thing = mystuff() thing.apple() print thing.tangerine 第一个类 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 relly around the family","With pockets full of shells"]) happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song()
Happy birthday to you I don't want to get sued So I'll stop right there they relly around the family With pockets full of shells 继承 你必须明白一个重要的概念,就是类和对象的不同。问题是,类和对象没有真正的区别,他们在不同的时间是相同的东西,我将用禅语解释他们: 鱼和鲑鱼的区别是什么呢? 这个问题是不是很晕?坐下来想想,我的意思是,鱼和鲑鱼是不同的,但是又是相同的,对吗?鲑鱼是鱼的一种,所以没有什么不同。但是,鲑鱼是鱼的一个分类,并且和其他鱼的分类不同。所以鲑鱼和鱼既相同又不同。 我们不需要真的知道鲑鱼和鱼的区别,只要知道鲑鱼是鱼的一种,而鱼还有其他很多种类就可以了。 现在让我们更近一步,假设你有三条鲑鱼,并且给他们取名为Frank,Joe,Mary,那么思考这个问题: Mary和鲑鱼有什么区别? 这也是一个奇怪的问题,但是比上个问题简单一点。你知道Mary是一条鲑鱼,她是鲑鱼的一个实例。Joe和Frank也是一个鲑鱼的实例。但是我们说的实例是什么意思呢?意思就是他们创建于鲑鱼,然后现在是一个真实东西,鲑鱼就像他们的属性。 现在记住了:鱼是一个类,鲑鱼也是一个类,Mary是一个对象。好好想想,你能明白过来的。 鱼是一个类,就是说鱼不是一个真正存在的东西,但是我们通过它的相似的特点去实例化一些东西,比如,有鳞片,有鳃,生活在水里等,那么这个东西就是一条鱼。 然后一个专家过来说:”这些鱼是鲑鱼。“ 这个专家给这些鱼定义一个新类”鲑鱼“,这个类有一些特别的属性,长鼻子,红色的肉,生活在海里,味道美味,好吧,它就是鲑鱼。 最后,一个厨师过来对专家说:不,你看到的鲑鱼在这里,我叫它Mary,我要把她做成一道美味。”现在,你就有了一个鲑鱼的实例(也是鱼的实例)叫做Mary,我们叫这个实例是一个对象。 现在我们得出:Mary是一种鲑鱼,鲑鱼是一种鱼。对象是一个类,而类又是另外一个类。 写成代码是这样的 第一,你要学习两个短语“is-a”和“has-a”。is-a就是对象和类之间通过类的关系想关联,has-a是对象和类相关联是因为他们彼此参考。 下面用这两个关系标注下面的程序,记住,鱼和鲑鱼是is-a的关系,鲑鱼和鳃是has-a的关系。 ## Animal is-a object (yes,sort of confusing) look at the extra credit class Animal(object): pass ## ?? is-a class Dog(Animal): def __init__(self,name): ## ?? has-a self.name = name ## ?? is-a class Cat(Animal): def __init__(self,name): ## ?? has-a self.name = name ## ?? is-a class Person(object): def __init__(self,name): ## ?? has-a self.name = name ## Person has-a pet of some kind self.pet = None ## ?? has-a class Employee(Person): def __init__(self,name,salary): ## ?? hmm what is this strange magic? super(Employee,self).__init__(name) ## ?? has-a self.salary = salary ## ?? is-a class Fish(object): pass ## ?? is-a class Salmon(Fish): pass ## ?? is-a class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? is-a satan = Cat("Satan") ## ?? is-a mary = Person("Mary") ## ?? is-a mary.pet = satan ## ?? is-a frank = Employee("Frank",120000) ## ?? is-a frank.pet = rover ## ?? is-a flipper = Fish() ## ?? is-a crouse = Salmon() ## ?? is-a harry = Halibut() 关于 class Name(object) 最初python设计类的时候有很多问题,等发现的时候已经太晚了,它们必须要支持这种错误的类。为了修正这个问题,他们必须设计一个新类方便旧的类能继续使用,而且新的类也能正确使用。 这就是为什么类要继承object类,是不是有点混乱,这里的object指的是类,而不是字面上的解释为对象。 你就记住,一个新的顶级类必须继承object就好了。不要太多纠结于字面上的理解,我们要留着思考更加重要的事情。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |