Python中的对象,方法,类,实例,函数用法分析


Posted in Python onJanuary 15, 2015

本文实例分析了Python中的对象,方法,类,实例,函数用法。分享给大家供大家参考。具体分析如下:

Python是一个完全面向对象的语言。不仅实例是对象,类,函数,方法也都是对象。

class Foo(object):

    static_attr = True

    def method(self):

        pass

foo = Foo()

这段代码实际上创造了两个对象,Foo和foo。而Foo同时又是一个类,foo是这个类的实例。
在C++里类型定义是在编译时完成的,被储存在静态内存里,不能轻易修改。在Python里类型本身是对象,和实例对象一样储存在堆中,对于解释器来说类对象和实例对象没有根本上的区别。
在Python中每一个对象都有自己的命名空间。空间内的变量被存储在对象的__dict__里。这样,Foo类有一个__dict__, foo实例也有一个__dict__,但这是两个不同的命名空间。
所谓“定义一个类”,实际上就是先生成一个类对象,然后执行一段代码,但把执行这段代码时的本地命名空间设置成类的__dict__. 所以你可以写这样的代码:
>>> class Foo(object):

...     bar = 1 + 1

...     qux = bar + 1

...     print "bar: ", bar

...     print "qux: ", qux

...     print locals()

...

bar:  2

qux:  3

{'qux': 3, '__module__': '__main__', 'bar': 2}

>>> print Foo.bar, Foo.__dict__['bar']

2 2

>>> print Foo.qux, Foo.__dict__['qux']

3 3

所谓“定义一个函数”,实际上也就是生成一个函数对象。而“定义一个方法”就是生成一
个函数对象,并把这个对象放在一个类的__dict__中。下面两种定义方法的形式是等价的:

>>> class Foo(object):

...     def bar(self):

...         return 2

...

>>> def qux(self):

...     return 3

...

>>> Foo.qux = qux

>>> print Foo.bar, Foo.__dict__['bar']
>>> print Foo.qux, Foo.__dict__['qux']
>>> foo = Foo()

>>> foo.bar()

2

>>> foo.qux()

3

而类继承就是简单地定义两个类对象,各自有不同的__dict__:

>>> class Cheese(object):

...     smell = 'good'

...     taste = 'good'

...

>>> class Stilton(Cheese):

...     smell = 'bad'

...

>>> print Cheese.smell

good

>>> print Cheese.taste

good

>>> print Stilton.smell

bad

>>> print Stilton.taste

good

>>> print 'taste' in Cheese.__dict__

True

>>> print 'taste' in Stilton.__dict__

False

复杂的地方在`.`这个运算符上。对于类来说,Stilton.taste的意思是“在Stilton.__dict__中找'taste'. 如果没找到,到父类Cheese的__dict__里去找,然后到父类的父类,等等。如果一直到object仍没找到,那么扔一个AttributeError.”
实例同样有自己的__dict__:

>>> class Cheese(object):

...     smell = 'good'

...     taste = 'good'

...     def __init__(self, weight):

...         self.weight = weight

...     def get_weight(self):

...         return self.weight

...

>>> class Stilton(Cheese):

...     smell = 'bad'

...

>>> stilton = Stilton('100g')

>>> print 'weight' in Cheese.__dict__

False

>>> print 'weight' in Stilton.__dict__

False

>>> print 'weight' in stilton.__dict__

True

不管__init__()是在哪儿定义的, stilton.__dict__与类的__dict__都无关。
Cheese.weight和Stilton.weight都会出错,因为这两个都碰不到实例的命名空间。而
stilton.weight的查找顺序是stilton.__dict__ => Stilton.__dict__ =>
Cheese.__dict__ => object.__dict__. 这与Stilton.taste的查找顺序非常相似,仅仅是
在最前面多出了一步。

方法稍微复杂些。

>>> print Cheese.__dict__['get_weight']
>>> print Cheese.get_weight
>>> print stilton.get_weight

<__main__.Stilton object at 0x7ff820669190>>

我们可以看到点运算符把function变成了unbound method. 直接调用类命名空间的函数和点
运算返回的未绑定方法会得到不同的错误:
>>> Cheese.__dict__['get_weight']()

Traceback (most recent call last):

  File "", line 1, in

TypeError: get_weight() takes exactly 1 argument (0 given)

>>> Cheese.get_weight()

Traceback (most recent call last):

  File "", line 1, in

TypeError: unbound method get_weight() must be called with Cheese instance as

first argument (got nothing instead)

但这两个错误说的是一回事,实例方法需要一个实例。所谓“绑定方法”就是简单地在调用方法时把一个实例对象作为第一个参数。下面这些调用方法是等价的:
>>> Cheese.__dict__['get_weight'](stilton)

'100g'

>>> Cheese.get_weight(stilton)

'100g'

>>> Stilton.get_weight(stilton)

'100g'

>>> stilton.get_weight()

'100g'

最后一种也就是平常用的调用方式,stilton.get_weight(),是点运算符的另一种功能,将stilton.get_weight()翻译成stilton.get_weight(stilton).
这样,方法调用实际上有两个步骤。首先用属性查找的规则找到get_weight, 然后将这个属性作为函数调用,并把实例对象作为第一参数。这两个步骤间没有联系。比如说你可以这样试:
>>> stilton.weight()

Traceback (most recent call last):

  File "", line 1, in

TypeError: 'str' object is not callable

先查找weight这个属性,然后将weight做为函数调用。但weight是字符串,所以出错。要注意在这里属性查找是从实例开始的:
>>> stilton.get_weight = lambda : '200g'

>>> stilton.get_weight()

'200g'

但是
>>> Stilton.get_weight(stilton)

'100g'

Stilton.get_weight的查找跳过了实例对象stilton,所以查找到的是没有被覆盖的,在Cheese中定义的方法。

getattr(stilton, 'weight')和stilton.weight是等价的。类对象和实例对象没有本质区别,getattr(Cheese, 'smell')和Cheese.smell同样是等价的。getattr()与点运算符相比,好处是属性名用字符串指定,可以在运行时改变。

__getattribute__()是最底层的代码。如果你不重新定义这个方法,object.__getattribute__()和type.__getattribute__()就是getattr()的具体实现,前者用于实例,后者用以类。换句话说,stilton.weight就是object.__getattribute__(stilton, 'weight'). 覆盖这个方法是很容易出错的。比如说点运算符会导致无限递归:

def __getattribute__(self, name):

        return self.__dict__[name]

__getattribute__()中还有其它的细节,比如说descriptor protocol的实现,如果重写很容易搞错。

__getattr__()是在__dict__查找没找到的情况下调用的方法。一般来说动态生成属性要用这个,因为__getattr__()不会干涉到其它地方定义的放到__dict__里的属性。

>>> class Cheese(object):

...     smell = 'good'

...     taste = 'good'

...

>>> class Stilton(Cheese):

...     smell = 'bad'

...     def __getattr__(self, name):

...         return 'Dynamically created attribute "%s"' % name

...

>>> stilton = Stilton()

>>> print stilton.taste

good

>>> print stilton.weight

Dynamically created attribute "weight"

>>> print 'weight' in stilton.__dict__

False

由于方法只不过是可以作为函数调用的属性,__getattr__()也可以用来动态生成方法,但同样要注意无限递归:
>>> class Cheese(object):

...     smell = 'good'

...     taste = 'good'

...     def __init__(self, weight):

...         self.weight = weight

...

>>> class Stilton(Cheese):

...     smell = 'bad'

...     def __getattr__(self, name):

...         if name.startswith('get_'):

...             def func():

...                 return getattr(self, name[4:])

...             return func

...         else:

...             if hasattr(self, name):

...                 return getattr(self, name)

...             else:

...                 raise AttributeError(name)

...

>>> stilton = Stilton('100g')

>>> print stilton.weight

100g

>>> print stilton.get_weight
>>> print stilton.get_weight()

100g

>>> print stilton.age

Traceback (most recent call last):

  File "", line 1, in

  File "", line 12, in __getattr__

AttributeError: age

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
详解Python迭代和迭代器
Mar 28 Python
python实现用户登录系统
May 21 Python
一个基于flask的web应用诞生 使用模板引擎和表单插件(2)
Apr 11 Python
Python 私有函数的实例详解
Sep 11 Python
python+numpy按行求一个二维数组的最大值方法
Jul 09 Python
pytorch模型预测结果与ndarray互转方式
Jan 15 Python
python实现飞机大战项目
Mar 11 Python
Python使用sqlite3模块内置数据库
May 07 Python
Python通过类的组合模拟街道红绿灯
Sep 16 Python
python如何构建mock接口服务
Jan 28 Python
python第三方网页解析器 lxml 扩展库与 xpath 的使用方法
Apr 06 Python
python如何读取.mtx文件
Apr 22 Python
Python转换HTML到Text纯文本的方法
Jan 15 #Python
python中os操作文件及文件路径实例汇总
Jan 15 #Python
python私有属性和方法实例分析
Jan 15 #Python
python实现堆栈与队列的方法
Jan 15 #Python
python多线程用法实例详解
Jan 15 #Python
Python中os.path用法分析
Jan 15 #Python
python静态方法实例
Jan 14 #Python
You might like
DC最新动画电影:《战争之子》为何内容偏激,毁了一个不错的漫画
2020/04/09 欧美动漫
php 文件上传系统手记
2009/10/26 PHP
php 调试利器debug_print_backtrace()
2012/07/23 PHP
php魔术变量用法实例详解
2014/11/13 PHP
php5.3后静态绑定用法详解
2016/11/11 PHP
利用Homestead快速运行一个Laravel项目的方法详解
2017/11/14 PHP
IE innerHTML,outerHTML所引起的问题
2009/06/04 Javascript
js设置组合快捷键/tabindex功能的方法
2013/11/21 Javascript
用js代码和插件实现wordpress雪花飘落效果的四种方法
2014/12/15 Javascript
js实现点击每个li节点,都弹出其文本值及修改
2016/12/15 Javascript
jQuery Easyui datagrid editor为combobox时指定数据源实例
2016/12/19 Javascript
JS无缝滚动效果实现方法分析
2016/12/21 Javascript
javascript 中Cookie读、写与删除操作
2017/03/29 Javascript
将angular-ui的分页组件封装成指令的方法详解
2017/05/10 Javascript
ExtJs的Ext.Ajax.request实现waitMsg等待提示效果
2017/06/14 Javascript
在漏洞利用Python代码真的很爽
2007/08/26 Python
Python实现定时精度可调节的定时器
2018/04/15 Python
使用python画个小猪佩奇的示例代码
2018/06/06 Python
python 平衡二叉树实现代码示例
2018/07/07 Python
python实现多张图片拼接成大图
2019/01/15 Python
Python动态赋值的陷阱知识点总结
2019/03/17 Python
python之pyqt5通过按钮改变Label的背景颜色方法
2019/06/13 Python
使用PyQt4 设置TextEdit背景的方法
2019/06/14 Python
Cython编译python为so 代码加密示例
2019/12/23 Python
Django基于Models定制Admin后台实现过程解析
2020/11/11 Python
18-35岁旅游团的全球领导者:Contiki
2017/02/08 全球购物
Tech21美国/加拿大:英国NO.1防摔保护壳品牌
2018/01/20 全球购物
Myprotein俄罗斯官网:欧洲第一运动营养品牌
2019/05/05 全球购物
眼镜促销方案
2014/03/15 职场文书
旅游管理毕业生自荐信范文
2014/03/19 职场文书
大学生村官承诺书
2014/03/28 职场文书
高三霸气励志标语
2014/06/24 职场文书
2014年财务人员工作总结
2014/11/11 职场文书
先进个人推荐材料
2014/12/29 职场文书
解析laravel使用workerman用户交互、服务器交互
2021/04/28 PHP
java objectUtils 使用可能会出现的问题
2022/02/28 Java/Android