免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1698 | 回复: 0
打印 上一主题 下一主题

《python 从入门到精通》§7 更多抽象:对象 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-18 08:32 |只看该作者 |倒序浏览


  Normal
  0
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  MicrosoftInternetExplorer4



/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.0pt;
        font-family:"Times New Roman";
        mso-fareast-font-family:"Times New Roman";
        mso-ansi-language:#0400;
        mso-fareast-language:#0400;
        mso-bidi-language:#0400;}

§7 更多抽象:对象
§7.1  对象的作用
多态、封装、继承
多态:
# Don't do it like this...
def getPrice(object):
if isinstance(object, tuple):
return object[1]
else:
return magic_network_method(object)



§7.2 类及类型
__metaclass__ = type # Make sure we get new
style classes
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello, world! I'm %s." %
self.nam

       __metaclass__
= type表示使用新的类。使其作为一个新类的子类也可以做到这点。
      
       >>>
class Class:
def method(self):
print 'I have a self!'
>>> def function():
print "I don't..."
>>> instance = Class()
>>> instance.method()
I have a self!
>>> instance.method = function
>>> instance.method()
I don't...

python间接支持private,如下的__inaccessible即为私有的。
class Secretive:
def __inaccessible(self):
print "Bet you can't see me..."
def accessible(self):
print "The secret message is:"
self.__inaccessible()

但是依然可以这样访问:
>>> s._Secretive__inaccessible()
Bet you can't see me...

import * 不会导入下划线开头的方法。

指定父类:

class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in
self.blocked]
class SPAMFilter(Filter): # SPAMFilter is a
subclass of Filter
def init(self): # Overrides init method
from Filter superclass
self.blocked = ['SPAM']

>>> s = SPAMFilter()
>>> s.init()
>>> s.filter(['SPAM', 'SPAM',
'SPAM', 'SPAM', 'eggs', 'bacon', 'SPAM'])
['eggs', 'bacon']

>>> issubclass(SPAMFilter, Filter)
True

>>> SPAMFilter.__bases__
(,)
>>> Filter.__bases__
()

>>> s = SPAMFilter()
>>> isinstance(s, SPAMFilter)
True
>>> isinstance(s, Filter)
True
>>> isinstance(s, str)
False
       isinstance往往不如多态可靠。
      
多继承:
       class
Calculator:
def calculate(self, expression):
self.value = eval(expression)
class Talker:
def talk(self):
print 'Hi, my value is', self.value
class TalkingCalculator(Calculator,
Talker):
pass
       如果方法相同,前面一个父类重载后面父类的。
      
       检查属性是否存在
       >>>
hasattr(tc, 'talk')
True
>>> hasattr(tc, 'fnord')
False
       检查函数是否可以调用:
       >>>
callable(getattr(tc, 'talk', None))
True
       callable在3.0要使用:hasattr(x, '__call__').
      
       修改属性:
       >>>
setattr(tc, 'name', 'Mr. Gumby')
>>> tc.name
'Mr. Gumby
       查看一个对象中的所有属性:__dict__。inspect模块可以查看一个对象的组成。

§7.3 面向对象设计

               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2030328.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP