上一页 1 ··· 3 4 5 6 7 8 9 10 下一页
摘要: 数学运算 Python 提供的基本数据类型 int、float 可以做整数和浮点的四则运算以及乘方等运算。 但是,四则运算不局限于int和float,还可以是有理数、矩阵等。 要表示有理数,可以用一个Rational类来表示: class Rational(object): def __init__ 阅读全文
posted @ 2020-02-08 22:19 搞点薯条 阅读(260) 评论(0) 推荐(0) 编辑
摘要: __len__ 如果一个类表现得像一个list,要获取有多少个元素,就得用 len() 函数。 要让 len() 函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数。 例如,我们写一个 Students 类,把名字传进去: class Students(object): def 阅读全文
posted @ 2020-02-08 22:12 搞点薯条 阅读(379) 评论(0) 推荐(0) 编辑
摘要: __cmp__ 对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 __cmp__(): class Student(object): def __init__( 阅读全文
posted @ 2020-02-08 21:57 搞点薯条 阅读(322) 评论(0) 推荐(0) 编辑
摘要: __str__和__repr__ 如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender de 阅读全文
posted @ 2020-02-08 21:30 搞点薯条 阅读(172) 评论(0) 推荐(0) 编辑
摘要: 特殊方法 python如何把任意数据类型变成str 因为任意数据类型都有一个特殊方法__str__() print(p) == print(p.__str__()) print(list) == print(list.__str__()) 特殊方法还有 特点 定义在class中 不需要直接调用 py 阅读全文
posted @ 2020-02-08 17:53 搞点薯条 阅读(157) 评论(0) 推荐(0) 编辑
摘要: 获取对象信息 拿到一个变量,除了用 isinstance() 判断它是否是某种类型的实例外,还有没有别的方法获取到更多的信息呢? 例如,已有定义: class Person(object): def __init__(self, name, gender): self.name = name sel 阅读全文
posted @ 2020-02-08 17:14 搞点薯条 阅读(195) 评论(0) 推荐(0) 编辑
摘要: 多重继承 除了从一个父类继承外,Python允许从多个父类继承,称为多重继承。 多重继承的继承链就不是一棵树了,它像这样: class A(object): def __init__(self, a): print 'init A...' self.a = a class B(A): def __i 阅读全文
posted @ 2020-02-08 16:56 搞点薯条 阅读(240) 评论(0) 推荐(0) 编辑
摘要: 多态 类具有继承关系,并且子类类型可以向上转型看做父类类型,如果我们从 Person 派生出 Student和Teacher ,并都写了一个 whoAmI() 方法: class Person(object): def __init__(self, name, gender): self.name 阅读全文
posted @ 2020-02-08 16:09 搞点薯条 阅读(156) 评论(0) 推荐(0) 编辑
摘要: 判断类型 函数isinstance()可以判断一个变量的类型,既可以用在Python内置的数据类型如str、list、dict,也可以用在我们自定义的类,它们本质上都是数据类型。 假设有如下的 Person、Student 和 Teacher 的定义及继承关系如下: class Person(obj 阅读全文
posted @ 2020-02-08 15:59 搞点薯条 阅读(652) 评论(0) 推荐(0) 编辑
摘要: 继承基础 继承的优点 新类不用从头编写,复用已有代码 新类从现有的类继承,就自动拥有了现有类的全部功能 新类只需要编写现有类缺少的功能 继承的特点 子类和父类是一个is关系 class person(object): pass class student(person): pass p = pers 阅读全文
posted @ 2020-02-08 15:51 搞点薯条 阅读(222) 评论(0) 推荐(0) 编辑
上一页 1 ··· 3 4 5 6 7 8 9 10 下一页