转载请标明出处:

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. 决策树遇到sklearn.exceptions.NotFittedError: XXX instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.的解决方案

    1.异常信息: C:\Python36\python36.exe "E:/python_project/ImoocDataAnalysisMiningModeling/第6章 挖掘建模/6- ...

  2. Django 模板语言从后端传到前端

    如果我们在后端有数据动态提取到前端的时候 就需要模板语言加以渲染后再将渲染好的HTML文件传入前端 我们的views.py里的index函数里有个s变量是个列表,将数据以大括号的形式传入{" ...

  3. WebUtility(提供在处理 Web 请求时用于编码和解码 URL 的方法。)

    public static string UrlEncode( string str ) UrlEncode(String) 方法可用来编码整个 URL,包括查询字符串值. 如果没有编码情况下,如空格 ...

  4. 【原】Ajax技术原理

    主要内容: Ajax原理 Ajax核心技术 Ajax是Asynchronous JavaScript and XML的简称,意思是异步的JavaScript和XML. 主要包括技术: web标准的XH ...

  5. CSS级联样式表-css选择器

    CSS概念 Cascading Style sheet 级联样式表 表现HTMl或XHTML文件样式的计算机语言 包括对字体,颜色,边距,高度,宽度,背景图片,网页定位等设定 建议:把表示样式的代码从 ...

  6. C# 时间操作类

    using System; namespace DotNet.Utilities { /// <summary> /// 时间类 /// 1.SecondToMinute(int Seco ...

  7. springboot在阿里CentOS 7后台永久运行

    查看Java进程可以使用 ps -ef|grep java 首次后台永久启动,会把日志输出到新建的log.file文件 nohup java -jar demo-0.0.1-SNAPSHOT.jar ...

  8. Python Django ORM创建基本类以及生成数据结构

    #在项目目录下的modules.py中创建一个类,来自动生成一张表UserInfo class UserInfo(models.Model): username = models.CharField( ...

  9. HtmlEntities

    #region GetOnlyTextFromHtmlCode + RemoveHtmlChars + RemoveTagFromHtmlCode /// <summary> /// ht ...

  10. Python3.7安装Geenlet

    1.首先再python文件下的Scripts文件夹下有这几个文件: 2.打开Scripts文件夹下可能你会发现是空的,这时候就要先安装setuptools了,安装完后Script文件下就出现上图的文件 ...