魔法方法、属性

------------------------

准备工作

为了确保类是新型类,应该把 _metaclass_=type 入到你的模块的最开始。

class NewType(Object):
  mor_code_here
class OldType:
  mor_code_here

在这个两个类中NewType是新类,OldType是属于旧类,如果前面加上 _metaclass_=type ,那么两个类都属于新类。

构造方法

构造方法与其的方法不一样,当一个对象被创建会立即调用构造方法。创建一个python的构造方法很简答,只要把init方法,从简单的init方法,转换成魔法版本的_init_方法就可以了。

class FooBar:
def __init__(self):
self.somevar = 42 >>> f =FooBar()
>>> f.somevar
42

重写一个一般方法

每一个类都可能拥有一个或多个超类(父类),它们从超类那里继承行为方法。

class A:
def hello(self):
print 'hello . I am A.'
class B(A):
  pass >>> a = A()
>>> b = B()
>>> a.hello()
hello . I am A.

因为B类没有hello方法,B类继承了A类,所以会调用A 类的hello方法。

在子类中增加功能功能的最基本的方式就是增加方法。但是也可以重写一些超类的方法来自定义继承的行为。如下:

class A:
def hello(self):
print 'hello . I am A.'
class B(A):
def hello(self):
print 'hello . I am B' >>> b = B()
>>> b.hello()
hello . I am B

特殊的和构造方法

重写是继承机制中的一个重要内容,对一于构造方法尤其重要。看下面的例子:

class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'Aaaah...'
self.hungry = False
else:
print 'No, thanks!' >>> b = Bird()
>>> b.eat()
Aaaah...
>>> b.eat()
No, thanks!

这个类中定义了鸟有吃的能力, 当它吃过一次后再次就会不饿了,通过上面的执行结果可以清晰的看到。

那么用SongBird类来继承Bird 类,并且给它添加歌唱的方法:

class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'Aaaah...'
self.hungry = False
else:
print 'No, thanks!' class SongBird(Bird):
def __init__(self):
self.sound = 'Squawk!'
def sing(self):
print self.sound >>> s = SongBird()
>>> s.sing()
Squawk!
>>> s.eat() Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
s.eat()
File "C:/Python27/bird", line 6, in eat
if self.hungry:
AttributeError: 'SongBird' object has no attribute 'hungry'

异常很清楚地说明了错误:SongBird没有hungry特性。原因是这样的:在SongBird中,构造方法被重写,但新的构造方法没有任何关于初始化hungry特性的代码。为了达到预期的效果,SongBird的构造方法必须调用其超类Bird的构造方法来确保进行基本的初始化。

两种方法实现:

一 、调用未绑定的超类构造方法

class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'Aaaah...'
self.hungry = False
else:
print 'No, thanks!' class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'Squawk!'
def sing(self):
print self.sound >>> s = SongBird()
>>> s.sing()
Squawk!
>>> s.eat()
Aaaah...
>>> s.eat()
No, thanks!

在SongBird类中添加了一行代码Bird.__init__(self) 。 在调用一个实例的方法时,该方法的self参数会被自动绑定到实例上(这称为绑定方法)。但如果直接调用类的方法,那么就没有实例会被绑定。这样就可以自由地提供需要的self参数(这样的方法称为未绑定方法)。

通过将当前的实例作为self参数提供给未绑定方法,SongBird就能够使用其超类构造方法的所有实现,也就是说属性hungry能被设置。

二、使用super函数

__metaclass__ = type  #表明为新式类
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'Aaaah...'
self.hungry = False
else:
print 'No, thanks!' class SongBird(Bird):
def __init__(self):
super(SongBird,self).__init__()
self.sound = 'Squawk!'
def sing(self):
print self.sound >>> s.sing()
Squawk!
>>> s.eat()
Aaaah...
>>> s.eat()
No, thanks!

super函数只能在新式类中使用。当前类和对象可以作为super函数的参数使用,调用函数返回的对象的任何方法都是调用超类的方法,而不是当前类的方法。那就可以不同在SongBird的构造方法中使用Bird,而直接使用super(SongBird,self)。

属性

访问器是一个简单的方法,它能够使用getHeight 、setHeight 之样的名字来得到或者重绑定一些特性。如果在访问给定的特性时必须要采取一些行动,那么像这样的封装状态变量就很重要。如下:

class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def setSize(self,size):
self.width , self.height = size
def getSize(self):
return self.width , self.height >>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.getSize()
(10, 5)
>>> r.setSize((150,100))
>>> r.width
150

在上面的例子中,getSize和setSize方法一个名为size的假想特性的访问器方法,size是由width 和height构成的元组。

property 函数

property函数的使用很简单,如果已经编写了一个像上节的Rectangle 那样的类,那么只要增加一行代码:

__metaclass__ = type
class Rectangle:
def __int__(self):
self.width = 0
self.height = 0
def setSize(self,size):
self.width, self.height = size
def getSize(self):
return self.width ,self.height
size = property(getSize ,setSize) >>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10, 5)
>>> r.size = 150,100
>>> r.width
150

在这个新版的Retangle 中,property 函数创建了一个属性,其中访问器函数被用作参数(先取值,然后是赋值),这个属性命为size 。这样一来就不再需要担心是怎么实现的了,可以用同样的方式处理width、height 和size。

python基础学习笔记(十)的更多相关文章

  1. 0003.5-20180422-自动化第四章-python基础学习笔记--脚本

    0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...

  2. Python基础学习笔记(十二)文件I/O

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-files-io.html ▶ 键盘输入 注意raw_input函 ...

  3. Python基础学习笔记(十)日期Calendar和时间Timer

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-date-time.html 3. http://www.liao ...

  4. python 基础学习笔记(1)

    声明:  本人是在校学生,自学python,也是刚刚开始学习,写博客纯属为了让自己整理知识点和关键内容,当然也希望可以通过我都博客来提醒一些零基础学习python的人们.若有什么不对,请大家及时指出, ...

  5. Python 基础学习笔记(超详细版)

    1.变量 python中变量很简单,不需要指定数据类型,直接使用等号定义就好.python变量里面存的是内存地址,也就是这个值存在内存里面的哪个地方,如果再把这个变量赋值给另一个变量,新的变量通过之前 ...

  6. Python基础学习笔记(十三)异常

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-exceptions.html Python用异常对象(excep ...

  7. Python基础学习笔记(十一)函数、模块与包

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-functions.html 3. http://www.liao ...

  8. Python基础学习笔记(九)常用数据类型转换函数

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-variable-types.html 3. http://www ...

  9. Python基础学习笔记(八)常用字典内置函数和方法

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-dictionary.html 3. http://www.lia ...

  10. Python基础学习笔记(七)常用元组内置函数

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-tuples.html 3. http://www.liaoxue ...

随机推荐

  1. 基于python的快速傅里叶变换FFT(二)

    基于python的快速傅里叶变换FFT(二)本文在上一篇博客的基础上进一步探究正弦函数及其FFT变换. 知识点  FFT变换,其实就是快速离散傅里叶变换,傅立叶变换是数字信号处理领域一种很重要的算法. ...

  2. .NET Core tasks.json 简介

    1.执行命令:dotnet> dotnet new console -o myApp 2.tasks.json文件配置: { "version": "2.0.0&q ...

  3. Linux 小知识翻译 - 「单CD 的linux」

    这次聊聊「单CD Linux」. 所谓「单CD Linux」,就是不用安装,从CD-ROM启动后就可以使用的Linux. 有名的KNOPPIX就是「单CD Linux」,此外还有Puppy Linux ...

  4. 启用crontab

    1.登录到root用户. 2.在root下输入:crontab -e 3.可能会提示你: no crontab for root - using an empty one 然后会叫你“Select a ...

  5. <20190102>收录些比较低级错误导致的主板故障现象

    今天收录俩个比较低级的错误. 故障现象:   水冷排风扇高速运转, 并无法调控. 现在CPU散热的水冷排都设计了三条线,   温控4Pin , 水泵线 3Pin  , 接在机箱上USB口取电的灯线或者 ...

  6. arcgis如何求两个栅格数据集的差集

    栅格数据集没有擦除功能,现在有栅格A和栅格B,怎么求两个栅格的差集C 具体步骤如下: 1.首先利用栅格计算器,把栅格B中的value全部赋值为0 输入语句:"栅格B" * 0 2  ...

  7. 【Ansible 文档】【译文】Playbooks 变量

    Variables 变量 自动化的存在使得重复的做事情变得很容易,但是我们的系统不可能完全一样. 在某些系统中,你可能想要设置一些与其他系统不一样的行为和配置. 同样地,远程系统的行为和状态也可以影响 ...

  8. el-table-column v-if条件渲染报错h.$scopedSlots.default is not a function

    我们在实际项目中经常会遇到el-table-column条件渲染出现报错的情况 报错内容: h.$scopedSlots.default is not a function 究其原因,是因为表格是el ...

  9. BookStrap之模板继承

    模板继承 (extend) Django模版引擎中最强大也是最复杂的部分就是模版继承了.模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 block ...

  10. session、cookie 记住登录状态的实现

    Cookie的机制 Cookie是浏览器(User Agent)访问一些网站后,这些网站存放在客户端的一组数据,用于使网站等跟踪用户,实现用户自定义功能. Cookie的Domain和Path属性标识 ...