1、对象的属性 
    python一切皆对象,每个对象都可能有多个属性。python的属性有一套统一的管理方案。 
属性的__dict__系统 
    对象的属性可能来自于其类定义,叫做类属性;还可能是该对象实例自身定义的属性,叫做对象属性。类属性可能来自类定义自身,也可能根据定义继承而来。 
    对象的属性存储在对象的__dict__属性中,__dict__是一个词典,键为属性名,值为属性本身。例如:

class Bird(object):
feather = True class Chicken(Bird):
fly = False
def __init__(self, age):
self.age = age summer = chicken(2)
print Bird.__dict__
print Chicken.__dict__
print summer.__dict__ {'__dict__': <attribute '__dict__' of 'Bird' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Bird' objects>, 'feather': True, '__doc__': None} {'fly': False, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x2b91db476d70>} {'age': 2}

可以看出,对类或对象(实际类也是一类对象)调用__dict__方法,只是返回该类或对象新增的属性。如果只有一个对象,而不知道它的类以及其他信息的时候,可以利用__class__属性找到对象的类,然后调用类的__base__属性来查询父类。 
    可以通过__dict__来获取和设置对象的属性。

summer.__dict__['age'] = 3
print(summer.__dict__['age']) summer.age = 5
print(summer.age)

使用特殊方法__getattr__ 
    可以使用 __getattr__(self, name) 来查询即时生成的属性,当我们查询一个属性的时候,如果通过__dict__方法无法找到该属性,那么python会调用该对象的__getattr__方法

class bird(object):
feather = True class chicken(bird):
fly = False
def __init__(self, age):
self.age = age
def __getattr__(self, name):
if name == 'adult':
if self.age > 1.0: return True
else: return False
else: raise AttributeError(name) summer = chicken(2)
print(summer.adult)
summer.age = 0.5 #本身有age属性
print(summer.adult) #本省没有age属性,会调用__getattr__方法
print(summer.male) #本省没有age属性,会调用__getattr__方法,抛出异常 每个特性需要有自己的处理函数,而__getattr__可以将所有的即时生成属性放在同一个函数中处理。__getattr__可以根据函数名区别处理不同的属性。
比如上面我们查询属性名male的时候,raise AttributeError。

python中还有一个__getattribute__特殊方法,用于查询任意属性,而__getattr__只能用来查询不在__dict__系统中的属性。

2、闭包 
函数对象作用域 
    python中函数也是对象,函数对象也有其存活的范围,就是函数对象的作用域。函数对象用def语句定义,函数对象的作用域与def所在的层级相同。比如,在函数A中定义内部函数B,内部函数B只能在定义该函数A内部使用,不能在函数A外部使用。

def line_conf():
def line(x):
return 2*x+1
print(line(5)) # within the scope line_conf()
print(line(5)) # out of the scope

如果使用lambda定义函数,那么函数对象的作用域与lambda所在的层级相同。

闭包 
    函数是一个对象,所以可以作为某个函数的返回结果。

def line_conf():
b = 15
def line(x):
return 2*x+b
return line # return a function object b = 5
my_line = line_conf()
print(my_line(5))

line定义的隶属程序块中引用了高层级的变量b,但b信息存在于line的定义之外,成b为line的环境变量。line作为line_conf的返回值时,line中已经包含了b的取值(尽管b并不隶属于line). 
    一个函数和它的环境变量合在一起就构成了一个闭包。在python中,闭包就是一个包含有环境变量取值的函数对象,环境变量取值被保存在函数对象的__closure__属性中。比如:

def line_conf():
b = 15
def line(x):
return 2*x+b
return line # return a function object b = 5
my_line = line_conf()
print(my_line.__closure__)
print(my_line.__closure__[0].cell_contents)

__closure__里包含了一个元组,该元组中的每个元素都是cell类型的对象。

def line_conf(a, b):
def line(x):
return ax + b
return line line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5), line2(5))
只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,
闭包也具有提高代码可复用性的作用。

3、装饰器 
    装饰器是一种高级的python语法,装饰器可以对一个函数、方法或者类进行加工。 
(1)装饰函数和方法 
    装饰器经常用于对一些函数添加这些函数需要共同执行的一些操作。

#定义装饰器函数,装饰器名任意
def decorator(F):
def new_F(a, b):
print("input", a, b)
return F(a, b)
return new_F #返回一个可调用对象,该可调用对象以函数为参数 # get square sum
@decorator #使用装饰器进行装饰,在前面使用 @装饰器名
def square_sum(a, b):
return a**2 + b**2 # get square diff
@decorator
def square_diff(a, b):
return a**2 - b**2 print(square_sum(3, 4))
print(square_diff(3, 4))
#使用装饰器的效果等同于,将函数重定义
square_sum = decorator(square_sum)
square_sum(3, 4)

(2)含参的装饰器 
    装饰器允许我们在调用装饰器的时候提供其他参数,比如 @decorator(params..)

#a new wrapper layer
def pre_str(pre=''):
#old decorator
def decorator(F):
def newF(a, b):
print (pre + 'intput', a, b)
return F(a,b)
return newF
return decorator @pre_str('xxxfjdflsd') #提供装饰器参数
def square_num(a, b):
return a**2 + b**2

(3)装饰类 
    一个装饰器可以接收一个类,并返回一个类,达到加工类的效果。

def decorator(aClass):
class newClass(object):
def __init__(self, age):
self.total_display = 0
self.wrapped = aClass(age)
def display(self):
self.total_display += 1
print('total display', self.total_display)
self.wrapped.display()
return newClass @decorator
class Bird(object):
def __init__(self, age):
self.age = age
def display(self):
print('my age is', self.age) eagleLord = Bird(5)
for i in range(3):
eagleLord.dislay()

参考:

http://www.cnblogs.com/vamei/archive/2012/09/13/2682778.html

python语法笔记(四)的更多相关文章

  1. python语法笔记(三)

    1. 动态类型 python的变量不需要声明,在赋值时,变量可以赋值为任意的值.这和Python的动态类型语言相关. python对象是存在于内存中的实体,代码中写对象名,只是指向该对象的引用.引用和 ...

  2. Python学习笔记四

    一.装饰器 1.知识储备 函数对象 函数可以被引用 函数可以当参数传递 返回值可以是函数 可以当作容器的元素 def func1(): print (666) def func2(): print ( ...

  3. python语法(四)— 文件操作

    前面几天学习了一写python的基础语法,也学习了分支if,循环while和for.由于之前已经做过几年的开发了,所以我们知道,许多数据来源并不是靠键盘输入到程序中去的,而是通过数据库和文件来获取到的 ...

  4. python学习笔记四 迭代器,生成器,装饰器(基础篇)

    迭代器 __iter__方法返回一个迭代器,它是具有__next__方法的对象.在调用__next__方法时,迭代器会返回它的下一个值,若__next__方法调用迭代器 没有值返回,就会引发一个Sto ...

  5. python语法笔记(二)

    1. 循环对象 循环对象是一类特殊的对象,它包含一个next()方法(在python3中是 __next__()方法),该方法的目的是进行到下一个结果,而在结束一系列结果之后,举出 StopItera ...

  6. Python 语法笔记

    1.else与while结合 while a>0: pass else: pass #当a<=0时执行 2.with语法,无需关闭文件,python自动关闭 with open('a.tx ...

  7. python学习笔记(四)

    模块与包 python模块,一个.py文件 导入模块的语法: import importable  importable#可以是包或包中的模块 import importable1,....,impo ...

  8. python学习笔记四——循环及冒泡排序

    3.3.3 break 和 continue语句 break:跳出整个循环 continue:跳出当前循环继续后面的循环 例: x=int(input("please input the ' ...

  9. Python学习笔记四:面向对象编程

    一:定义类并创建实例 Python中定义类,通过class关键字,类名开头大写,参数列表为所继承的父类.如果没有需要明确继承的类,则继承object. 使用类来创建对象,只需 类名+() 形式即可,p ...

随机推荐

  1. Socket状态变迁图

    在一些防火墙或端口管理工具中经常会看到连接状态为CLOSED CLOSE_WITE LAST_ACK等的进程, 虽然状态就那么很少的几个, 而且看字面意思也能猜个大概, 但没做过Socket编程的朋友 ...

  2. muduo库安装

    一.简介 Muduo(木铎)是基于 Reactor 模式的网络库. 二.安装 从github库下载源码安装:https://github.com/chenshuo/muduo muduo依赖了很多的库 ...

  3. 解决保存快照失败后redis无法写入的问题

    用命令行工具连上后执行“set test 0”出现以下错误提示: MISCONF Redis is configured to save RDB snapshots, but is currently ...

  4. C#中另类自定义公式计算 字符串转换为计算公式,并得出计算结果

    [csharp] view plain copy print? //方法一 利用DataTable中的Compute方法 例如:1*2-(4/1)+2*4=6 , , , ); DataTable d ...

  5. C#中调用存储过程:带输入输出参数

    using (SqlConnection conn = new SqlConnection(this.GetConnectionString(this.WMPDBName))) { SqlComman ...

  6. fragment (1)简单示例:定义,界面配置,fragment之间的跳转

    fragment作用 同一程序中切换界面 比activity轻快,灵活. fragment代码示例 ide  : android studio 1.2 sdk : 22 package com.exa ...

  7. C语言第4天循环,流程控制。

    C语言第四天 :first-child { margin-top: 0; } blockquote > :last-child { margin-bottom: 0; } img { borde ...

  8. C# Ini配置文件

    public class INIUserAccound { static IniFile Ini = new IniFile(AppDomain.CurrentDomain.BaseDirectory ...

  9. js parseInt();parseFloat;Number()

    1:  parseInt( numString [, radix ] ) [测试浏览器:chromium && firefox] ①parseInt()函数用于将字符串转换为(十进制) ...

  10. heredoc 和 nowdoc

    heredoc 和 nowdoc     多次使用 php nowdoc HereDoc 插入大量Hmtl都没有成功,一样提示语法有问题,事实上PHP手册注明是这样写的,实在很奇怪 最后发现了问题所在 ...