• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python语言的面相对象编程方式初步学习

Python语言的面相对象编程方式初步学习

作者:goldensun 字体:[增加 减小] 来源:互联网

goldensun 通过本文主要向大家介绍了Python语言的面相对象编程方式初步学习等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

词语练习

  • class:告诉python创造一个新的东西
  • object:两个意思:最基本的东西和任何实例化的东西。
  • instance:创建一个类得到的东西。
  • def:在类中创建一个函数。
  • self:在类里面的函数中使用,是实例和object能访问的变量。
  • inheritance:继承,一个类可以继承另一个类,像你和你的父母。
  • composition:一个类可以包含另外一个类,就像汽车包含轮胎。
  • attribute:一个属性类,通常包括变量。
  • is-a:表示继承关系
  • has-a:包含关系

通过卡片记忆这些词语,单独的词语通常没什么意义,不过我还是要先知道它们的存在。

短语练习

  • 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函数,m函数有self和j两个参数。
  • foo = x():设置foo为类x的实例化。
  • foo.m(j):通过foo调用m函数,参数是self和j。
  • foo.k = q:通过foo给k属性赋值为q。

上面那些x,y,m,q等等都是可以变的。

一个阅读测试
这是一个简单的脚本可以让你用来做练习,它只做一件事,就是使用一个urllib的库去下载一个单词列表。我们把下面的代码写到opp_test.py文件中。

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):\n\tdef __init__(self, ***)" : "class ### has-a __init__ that takes self and *** parameters.", 
  "class ###(object):\n\tdef ***(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("***", word, 1) 
 
 
    # fake parameter lists 
    for word in param_names: 
      result = result.replace("@@@", word, 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: %s\n\n" % answer 
except EOFError: 
  print "\nBye" 

</div>


运行这个例子,它会尽可能准确的回答问题。

root@he-desktop:~/mystuff# python oop_test.py 
</div>
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, and call it with parameters self, arch.


cat = Aftermath()
> 
ANSWER: Set cat to an instance of class Aftermath.


cork.card = 'attempt'
> 

</div>


类和对象
类就像模块
你可以认为模块就是一个特殊的字典,它可以保存python代码,通过 . 号调用。python还有一个类似实现这种目的的结构,叫做类。一个类包含了很多函数和数据,可以通过 . 去访问它们。

如果我要写一个类似mystuff的类,就像这样:

class mystuff(object):
  def __int__(self):
    self.tangerine = "Hello"

  def apple(self):
    print "apple"

</div>

和模块比有点复杂,不过你可以认为它就是一个迷你模块。让人疑惑的是__init__()函数和self.tangerine设置tangerine变量的值。

这里是用类替代模块的原因:你可以在一个程序中使用同一个类很多次,它们不相互影响,但是一个程序中只能导入一个模块。

理解这些之前,你必须理解什么是对象。

对象就像迷你的导入
如果类像模块,那么类也会有类型模块的导入功能。就是实例化,如果你实例化一个类,得到的就是一个对象。

使用类的方法类似调用函数,像这样:

thing = mystuff()
thing.apple()
print thing.tangerine
</div>

第一步是实例化,然后调用它的函数,我们通过上面的代码分析一下python是怎么按照顺序执行的:

  • python寻找Myclass,看看你是不是定义了这个类。
  • python为你在类里面定义的函数创建一个空对象。
  • 如果类中有魔术方法__init__,那么就会使用这个函数初始化你的空对象。
  • 在__init__方法中有一个额外的变量self,这就是python为我们创建的空对象,你可以给这个变量赋值。
  • 这样的话,我给 thing.tangerine赋了句歌词,并且初始化了这个对象。
  • 那么现在python就可以把这个刚完成的对象赋给一个变量thing了。

这就是我们为什么像调用函数一样导入一个类。

记住,我给出的不是一个非常准确类的工作方法,仅仅是为了你能通过模块而更好的理解类。事实是,类和对象和模块不是一个东西,老实说的话,就像下面这样:

  • 类就像一个蓝图,定义用来创建一个迷你模块。
  • 实例化就是导入的同时使用这个迷你模块。
  • 创建出来的迷你模块就是对象,赋给一个变量,然后通过这个变量工作。
  • 虽然从模块过渡到类和对象比较难,不过也只有这个方法比较好理解。

从东西中取出东西
现在有三种方法:

# 字典
mystuff['apple']

# 模块
mystuff.apple()
print mystuff.tangerine

# 类
thing = mystuff()
thing.apple()
print thing.tangerine

</div>

第一个类
你可能还有很多疑问,不要着急,暂时先放放这些疑问,下一个练习我们学校面向对象的知识,下面我们先了解一下类的写法,为下一练习做准备。

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() 

</div>


运行结果

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
</div>

继承

你必须明白一个重要的概念,就是类和对象的不同。问题是,类和对象没有真正的区别,他们在不同的时间是相同的东西,我将用禅语解释他们:

鱼和鲑鱼的区别是什么呢?

这个问题是不是很晕?坐下来想想,我的意思是,鱼和鲑鱼是不同的,但是又是相同的,对吗?鲑鱼是鱼的一种,所以没有什么不同。但是,鲑鱼是鱼的一个分类,并且和其他鱼的分类不同。所以

您可能想查找下面的文章:

相关文章

  • python 实现删除文件或文件夹实例详解
  • Python基于Tkinter的HelloWorld入门实例
  • Python selenium 三种等待方式详解(必会)
  • pyqt4教程之实现半透明的天气预报界面示例
  • Python实现类似jQuery使用中的链式调用的示例
  • 在Python中操作时间之tzset()方法的使用教程
  • Python中强大的命令行库click入门教程
  • Python使用PDFMiner解析PDF代码实例
  • 解读Python编程中的命名空间与作用域
  • pyqt和pyside开发图形化界面

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 收藏整理的一些Python常用方法和技巧
    • Python使用迭代器捕获Generator返回值的方法
    • 简单谈谈python中的Queue与多进程
    • Python内置函数的用法实例教程
    • python解析html开发库pyquery使用方法
    • 分享Python字符串关键点
    • python代码制作configure文件示例
    • Mac下Supervisor进程监控管理工具的安装与配置
    • Windows中安装使用Virtualenv来创建独立Python环境
    • Python实现带百分比的进度条

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有