Python定制类
来源:互联网 发布:离线看书软件 编辑:程序博客网 时间:2024/05/16 08:48
定制类
打印类信息
class Person(object): def __init__(self, name, gender): self.name = name self.gender = genderclass 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
定义了 __str__ 和 __repr__方法,定制自己的类对象的打印信息
定义类的比较函数
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 -1 elif self.score < s.score: return 1 else: if self.name > s.name: return 1 else: return -1L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]print sorted(L)
定义len函数
class Fib(object): def __init__(self, num): self.num = num mylist = [0,1] for i in range(1,num-1): mylist.append(mylist[-1] + mylist[-2]) self.mylist = mylist def __str__(self): return '%s' %(self.mylist) def __len__(self): return len(self.mylist) f = Fib(10)print fprint len(f)
@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 >= 80: return 'A' elif self.score < 60: return 'C' else: return 'B's = Student('Bob', 59)print s.grades.score = 60print s.grades.score = 99print s.grade
限制类的属性
class Person(object): __slots__ = ('name', 'gender') def __init__(self, name, gender): self.name = name self.gender = genderclass Student(Person): __slots__ = ('name','gender','score') def __init__(self,name,gender,score): super(Student,self).__init__(name,gender) self.score = scores = Student('Bob', 'male', 59)s.name = 'Tim's.score = 99print s.score
__call__函数
class Fib(object): def __call__(self,num): mylist = [0,1] for i in range(1,num-1): mylist.append(mylist[-1] + mylist[-2]) return mylistf = Fib()print f(10)
一个类实例也可以成为一个可调用对象,需要实现__call__方法。
0 0
- python学习-定制类
- python定制类
- Python定制类
- Python定制类
- python 定制类
- python知识-定制类
- python 学习--定制类
- python定制类
- Python 7、定制类
- Python基础-定制类
- python定制类
- Python: 定制类
- python核心编程-定制类
- python学习笔记 定制类
- Python基础-定制类(str_iter_getItem_getattr_call)
- python 用特殊方法定制类
- 【python】继承 定制 使用元类
- python 包装类型 与定制类
- 简单的初学者配置Android SDK+ADT+Eclipse
- 安装Qt5 (一)
- ibatis返回插入后的自增id
- <Linux内核源码>文件系统VFS内核4.0.4版本基本概念源码
- 跨浏览器事件处理 EventUtil
- Python定制类
- 桥接模式
- C++ Vector 使用总结
- GMap —— 绘制点集
- android本地数据存贮之sqlite
- 【MyBatis框架】MyBatis入门程序第一部分
- ccccccccc
- => 运算符(C# 参考)
- 数据库 分布式系统的事务处理