---
title: "关于python中类的小总结2"
author: "saber7"
date: "2010-12-06T23:28:48Z"
tags: ["Blog", "Python"]
categories: ["编程语言"]
slug: "python-2"
draft: false
lastmod: "2010-12-06T23:29:53Z"
id: 835157
url: "https://saber7.iteye.com/blog/835157"
---

一、特殊方法定制类，看一个程序吧：  
class RoundFloatManual(object):  
    def \_\_init\_\_(self, val):  
        assert isinstance(val, float),"Value must be a float!"  
        self.value = round(val, 2)  
    def \_\_str\_\_(self):  
        return '%.2f' % self.value  
    \_\_repr\__ = \_\_str\__

&gt;&gt;&gt; r = RoundFloatManual(5.568)  
&gt;&gt;&gt; r  
5.57

加法：  
&gt;&gt;&gt; class Time60(object):  
    def \_\_init\_\_(self, hr, min):  
        self.hr = hr  
        self.min = min  
    def \_\_repr\_\_(self):  
        return '%d:%d' % (self.hr, self.min)  
    def \_\_add\_\_(self, other):  
        return self.\_\_class\_\_(self.hr + other.hr, self.min + other.min)

     
&gt;&gt;&gt; a = Time60(10, 30)  
&gt;&gt;&gt; b = Time60(5, 20)  
&gt;&gt;&gt; a + b  
15:50

原位加：  
class Time60(object):  
    def \_\_init\_\_(self, hr, min):  
        self.hr = hr  
        self.min = min  
    def \_\_repr\_\_(self):  
        return '%d:%d' % (self.hr, self.min)  
    def \_\_add\_\_(self, other):  
        return self.\_\_class\_\_(self.hr + other.hr, self.min + other.min)  
    def \_\_iadd\_\_(self, other):  
        self.hr += other.hr  
        self.min += other.min  
        return self  
&gt;&gt;&gt; a = Time60(10, 30)  
&gt;&gt;&gt; b = Time60(5, 20)  
&gt;&gt;&gt; a += b  
&gt;&gt;&gt; a  
15:50  
与上面一样，当使用到“+”加好的时候，就去自动调用\_\_add\_\_方法，使用到“+=”的时候就去调用\_\_iadd\_\_()方法。

迭代器  
&gt;&gt;&gt; from random import choice  
&gt;&gt;&gt; class RandSeq(object):  
    def \_\_init\_\_(self, seq):  
        self.data = seq  
    def \_\_iter\_\_(self):  
        return self  
    def next(self):  
        return choice(self.data)  
&gt;&gt;&gt; for eachItem in RandSeq(('rock', 'paper', 'scissors')):  
            print eachItem

             
scissors  
rock  
paper  
paper  
rock  
paper  
……

二、关于单双下划线开头的方法名  
Python 用下划线作为变量前缀和后缀指定特殊变量。

\_xxx      不能用'from module import \*'导入  
\_\_xxx\__ 系统定义名字  
\_\_xxx    类中的私有变量名

核心风格：避免用下划线作为变量名的开始。  
参考http://saber7.iteye.com/blog/835141

 

未完……

### [关于python中类的小总结1](../../../blog/834718)

### [关于python中类的小总结2](/blog/835157)