转载请标明出处:

http://www.cnblogs.com/why168888/p/6411919.html

本文出自:【Edwin博客园】

Python定制类(进阶6)

1. python中什么是特殊方法

任何数据类型的实例都有一个特殊方法:__str__()

  • 用于print的__str__
  • 用于len的__len__
  • 用于cmp的__cmp__
  • 特殊方法定义在class中
  • 不需要直接调用
  • Python的某些函数或操作符会调用对应的特殊方法

正确实现特殊方法

  • 只需要编写用到的特殊方法
  • 有关联性的特殊方法都必须实现
  • __getattr__,__setattr__,__delattr__

2. python中 __str__和__repr__

class Person(object):

    def __init__(self, name, gender):
self.name = name
self.gender = gender class Student(Person): def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score def __str__(self):
return '(Student: %s, %s, %s)' % (self.name, self.gender, self.score) __repr__ = __str__
s = Student('Bob', 'male', 88)
print s

3. python中 __cmp__

对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 __cmp__()

class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__ def __cmp__(self, s):
if self.name < s.name:
return -1
elif self.name > s.name:
return 1
else:
return 0 class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score def __str__(self):
return '(%s: %s)' % (self.name, self.score) __repr__ = __str__ def __cmp__(self, s):
if self.score == s.score:
return cmp(self.name, s.name)
return -cmp(self.score, s.score) L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)

4. python中 __len__

如果一个类表现得像一个list,要获取有多少个元素,就得用 len() 函数.

要让 len() 函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数。

class Students(object):
def __init__(self, *args):
self.names = args
def __len__(self):
return len(self.names)
ss = Students('Bob', 'Alice', 'Tim')
print len(ss) # 3 class Fib(object): def __init__(self, num):
a, b, L = 0, 1, []
for n in range(num):
L.append(a)
a, b = b, a + b
self.num = L def __len__(self):
return len(self.num) f = Fib(10)
print f.num # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
print len(f) # 10

5. python中数学运算

Python 提供的基本数据类型 int、float 可以做整数和浮点的四则运算以及乘方等运算。

def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b) class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q) def __sub__(self, r):
return Rational(self.p * r.q - self.q * r.p, self.q * r.q) def __mul__(self, r):
return Rational(self.p * r.p, self.q * r.q) def __div__(self, r):
return Rational(self.p * r.q, self.q * r.p) def __str__(self):
g = gcd(self.p, self.q)
return '%s/%s' % (self.p / g, self.q / g) __repr__ = __str__ r1 = Rational(1, 2)
r2 = Rational(1, 4)
print r1 + r2
print r1 - r2
print r1 * r2
print r1 / r2

6. python中类型转换

print int(12.34) # 12
print float(12) # 12.0 class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q def __int__(self):
return self.p // self.q def __float__(self):
return float(self.p) / self.q print float(Rational(7, 2)) # 3.5
print float(Rational(1, 3)) # 0.333333333333

7. python中 @property

class Student(object):

    def __init__(self, name, score):
self.name = name
self.__score = score @property
def score(self):
return self.__score @score.setter
def score(self, score):
if score < 0 or score > 100:
raise ValueError('invalid score')
self.__score = score @property
def grade(self):
if self.score < 60:
return 'C'
if self.score < 80:
return 'B'
return 'A' s = Student('Bob', 59)
print s.grade s.score = 60
print s.grade s.score = 99
print s.grade

8. python中 __slots__

slots 的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。

class Student(object):
__slots__ = ('name', 'gender', 'score')
def __init__(self, name, gender, score):
self.name = name
self.gender = gender
self.score = score s = Student('Bob', 'male', 59)
s.name = 'Tim' # OK
s.score = 99 # OK
s.grade = 'A' # Error class Person(object): __slots__ = ('name', 'gender') def __init__(self, name, gender):
self.name = name
self.gender = gender class Student(Person): __slots__ = {'score'} def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score s = Student('Bob', 'male', 59)
s.name = 'Tim'
s.score = 99
print s.score

9. python中__call__

一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()


class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender def __call__(self, friend):
print 'My name is %s...' % self.name
print 'My friend is %s...' % friend p = Person('Bob', 'male')
p('Tim') # My name is Bob... My friend is Tim... class Fib(object):
def __call__(self, num):
a, b, L = 0, 1, []
for n in range(num):
L.append(a)
a, b = b, a + b
return L f = Fib()
print f(10) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

10.下一步学习内容

  • IO:文件和Socket
  • 多线程:进程和线程
  • 数据库
  • Web开发

Python定制类(进阶6)的更多相关文章

  1. python定制类(1):__getitem__和slice切片

    python定制类(1):__getitem__和slice切片 1.__getitem__的简单用法: 当一个类中定义了__getitem__方法,那么它的实例对象便拥有了通过下标来索引的能力. c ...

  2. python 定制类

    看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的. __slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让cla ...

  3. python定制类详解

    1.什么是定制类python中包含很多内置的(Built-in)函数,异常,对象.分别有不同的作用,我们可以重写这些功能. 2.__str__输出对象 class Language(object): ...

  4. Python 定制类与其对象的创建和应用

    1.创建新类Athlete,创建两个唯一的对象实例sarah james,他们会继承Athlete类的特性 >>> class Athlete: def __init__(self, ...

  5. python定制类(以Fib类为例)

    class Fib(object): def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self def __n ...

  6. Python 定制类 特殊方法

    1.特殊方法 定义在class中 不需要直接调用,python的某些函数或操作符会自动的调用对应的特殊方法. 如定义了person类,使用print p 语句打印person类的实例时,就调用了特殊方 ...

  7. Python定制类

    https://docs.python.org/3/reference/datamodel.html#special-method-names

  8. python基础——定制类

    python基础——定制类 看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的. __slots__我们已经知道怎么用了,__len__()方 ...

  9. python学习(八)定制类和枚举

    `python`定制类主要是实现特定功能,通过在类中定义特定的函数完成特定的功能. class Student(object): def __init__(self, name): self.name ...

随机推荐

  1. Flume1.6.0搭建

    下载地址:http://archive.apache.org/dist/flume/ 解压完毕 切换到安装目录下/usr/local/flume/apache-flume-1.6.0-bin/conf ...

  2. 解决vue不相关组件之间的数据传递----vuex的学习笔记,解决报错this.$store.commit is not a function

    Vue的项目中,如果项目简单, 父子组件之间的数据传递可以使用  props 或者 $emit 等方式 进行传递 但是如果是大中型项目中,很多时候都需要在不相关的平行组件之间传递数据,并且很多数据需要 ...

  3. CodeIgniter 目录结构详解

    1. myshop 2. |-----system 框架程序目录 3. |-----core 框架的核心程序 4. |-----CodeIgniter.php 引导性文件 5. |-----Commo ...

  4. 动态rem解决移动前端适配

    背景 移动前端适配一直困扰很多人,我自己也是从最初的媒体查询,到后来的百分比,再到padding-top这种奇巧淫技,再到css3新单位vw这种过渡转变 但这些都或多或少会有些问题,直到使用了动态re ...

  5. table 中的tr 行点击 变换颜色背景

    <style> table{border-collapse: collapse;border-spacing: 0; width: 100%;} table tr th,td{border ...

  6. 微信小程序通过CODE换取session_key和openid

    微信小程序的用户信息获取需要请求微信的服务器,通过小程序提供的API在小程序端获取CODE,然后将CODE传入到我们自己的服务器,用我们的服务器来换取session_key和openid. 小程序端比 ...

  7. 前端(十二):react-redux实现逻辑

    一.context实现数据传递 在react中,props和state都可以设置数据.不同的是,props借助组件属性传递数据但不可以渲染组件,它相对来说是“静态的”:state可以监听事件来修改数据 ...

  8. csharp: Microsoft SqlHelper

    from: Microsoft Data Access Application Block for .NET  https://www.microsoft.com/en-us/download/con ...

  9. BZOJ3193: [JLOI2013]地形生成

    传送门 Sol 第一问可以考虑按照山的高度从大到小放 但是这样如果遇到高度相同的就不好考虑,那么同时要求数量限制从小到大 这样每次放的时候后面的一定不会影响前面,并且高度相同的时候前面能放的位置后面的 ...

  10. BZOJ1149 [CTSC2007]风玲

    Description Input Output 输出仅包含一个整数.表示最少需要多少次交换能使风铃满足Ike的条件.如果不可能满足,输出-1. Sample Input 6 2 3 -1 4 5 6 ...