Python定制类(进阶6)

1. python中什么是特殊方法

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

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

Python定制类(进阶6)-LMLPHP

正确实现特殊方法

  • 只需要编写用到的特殊方法
  • 有关联性的特殊方法都必须实现
  • __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开发
05-11 07:56