类和对象
类相关的bif
issubclass(class,classinfo) #classinfo可以是类对象组成的元组,只要class是其中任何一个候选类的子类,返回True
isinstance(object,classinfo) #与issubclass类似,如果第一个参数不是对象,则永远返回False,如果第二个参数不是类或者由类对象组成的元组,抛出TypeError的异常
hasattr(object,name) #测试一个对象是否有指定的属性,name要用字符串括起来
getattr(object,name[,default]) #测试一个对象是否有指定的属性,没有就返回default值,增强用户体验
setattr(object,name,value) #为对象的属性设置一个新值
delattr(object,name) #删除对象中指定属性,如果不存在抛出异常
### 上述bif都是调用了相应的魔法方法:
__getattr__(self,name)
__getattribute__(self,name)
__setattr__(self,name,value)
__delattr__(self,name)
继承
- 屏蔽父类方法:覆盖父类方法,例如将函数体内容写 pass
class Bird:
def fly(self):
print("Fly away!")
class Penguin(Bird):
def fly(self):
pass
>>> bird = Bird()
>>> penguin = Penguin()
>>> bird.fly()
Fly away!
>>> penguin.fly()
- super函数:填入基类的属性进行继承
super().__init__() #针对于init函数的使用方法,可以避免钻石继承的问题
静态属性和静态方法
尝试自己举一个例子说明如何使用类的静态属性。(一定要自己先动手再看答案哦_)
答:类的静态属性很简单,在类中直接定义的变量(没有 self.)就是静态属性。引用类的静态属性使用”类名.属性名”的形式。应用如下:
class C:
count = 0 # 静态属性
def __init__(self):
C.count = C.count + 1 # 类名.属性名的形式引用
def getCount(self):
return C.count
尝试自己举例说明如何使用类的静态方法,并指出使用类的静态方法有何有点和需要注意的地方?(一定要自己先动手再看答案哦_)
答:静态方法是类的特殊方法,静态方法只需要在普通方法的前边加上 @staticmethod 修饰符即可。
class C:
@staticmethod # 该修饰符表示 static() 是静态方法
def static(arg1, arg2, arg3):
print(arg1, arg2, arg3, arg1 + arg2 + arg3)
def nostatic(self):
print("I'm the f**king normal method!")
静态方法最大的优点是:不会绑定到实例对象上,换而言之就是节省开销。
>>> c1 = C()
>>> c2 = C()
# 静态方法只在内存中生成一个,节省开销
>>> c1.static is C.static
True
>>> c1.nostatic is C.nostatic
False
>>> c1.static
<function C.static at 0x03001420>
>>> c2.static
<function C.static at 0x03001420>
>>> C.static
<function C.static at 0x03001420>
# 普通方法每个实例对象都拥有独立的一个,开销较大
>>> c1.nostatic
<bound method C.nostatic of <__main__.C object at 0x03010590>>
>>> c2.nostatic
<bound method C.nostatic of <__main__.C object at 0x032809D0>>
>>> C.nostatic
<function C.nostatic at 0x0328D2B8>
使用的时候需要注意的地方:静态方法并不需要 self 参数,因此即使是使用对象去访问,self 参数也不会传进去。
>>> c1.static(1, 2, 3)
1 2 3 6
>>> C.static(1, 2, 3)
1 2 3 6
魔法方法
基础魔法方法
init(self)
- __init__特殊方法不应该返回除了None以外的任何对象
new(cls[,…])
- 先于init的一个魔法方法,返回值是一个对象,在继承的类是一个不可变的类而需要对他进行修改时使用,后面的参数会原封不动的给init
del(self)
- 垃圾回收机制,当没有变量(对象)引用时,会自动删掉,所以要所有对象都被删掉时,才会执行del方法
运算与反运算
Python 什么时候会调用到反运算的魔法方法?
答:例如 a + b,如果 a 对象的 add 方法没有实现或者不支持相应的操作,那么 Python 就会自动调用 b 的 radd 方法。
魔法方法列表
魔法方法 | 含义 |
---|---|
基本的魔法方法 | |
new(cls[, …]) | 1. new 是在一个对象实例化的时候所调用的第一个方法 2. 它的第一个参数是这个类,其他的参数是用来直接传递给 init 方法 3. new 决定是否要使用该 init 方法,因为 new 可以调用其他类的构造方法或者直接返回别的实例对象来作为本类的实例,如果 new 没有返回实例对象,则 init 不会被调用 4. new 主要是用于继承一个不可变的类型比如一个 tuple 或者 string |
init(self[, …]) | 构造器,当一个实例被创建的时候调用的初始化方法 |
del(self) | 析构器,当一个实例被销毁的时候调用的方法 |
call(self[, args…]) | 允许一个类的实例像函数一样被调用:x(a, b) 调用 x.call(a, b) |
len(self) | 定义当被 len() 调用时的行为 |
repr(self) | 定义当被 repr() 调用时的行为 |
str(self) | 定义当被 str() 调用时的行为 |
bytes(self) | 定义当被 bytes() 调用时的行为 |
hash(self) | 定义当被 hash() 调用时的行为 |
bool(self) | 定义当被 bool() 调用时的行为,应该返回 True 或 False |
format(self, format_spec) | 定义当被 format() 调用时的行为 |
有关属性 | |
getattr(self, name) | 定义当用户试图获取一个不存在的属性时的行为 |
getattribute(self, name) | 定义当该类的属性被访问时的行为 |
setattr(self, name, value) | 定义当一个属性被设置时的行为 |
delattr(self, name) | 定义当一个属性被删除时的行为 |
dir(self) | 定义当 dir() 被调用时的行为 |
get(self, instance, owner) | 定义当描述符的值被取得时的行为 |
set(self, instance, value) | 定义当描述符的值被改变时的行为 |
delete(self, instance) | 定义当描述符的值被删除时的行为 |
比较操作符 | |
lt(self, other) | 定义小于号的行为:x < y 调用 x.lt(y) |
le(self, other) | 定义小于等于号的行为:x <= y 调用 x.le(y) |
eq(self, other) | 定义等于号的行为:x == y 调用 x.eq(y) |
ne(self, other) | 定义不等号的行为:x != y 调用 x.ne(y) |
gt(self, other) | 定义大于号的行为:x > y 调用 x.gt(y) |
ge(self, other) | 定义大于等于号的行为:x >= y 调用 x.ge(y) |
算数运算符 | |
add(self, other) | 定义加法的行为:+ |
sub(self, other) | 定义减法的行为:- |
mul(self, other) | 定义乘法的行为:* |
truediv(self, other) | 定义真除法的行为:/ |
floordiv(self, other) | 定义整数除法的行为:// |
mod(self, other) | 定义取模算法的行为:% |
divmod(self, other) | 定义当被 divmod() 调用时的行为 |
pow(self, other[, modulo]) | 定义当被 power() 调用或 ** 运算时的行为 |
lshift(self, other) | 定义按位左移位的行为:<< |
rshift(self, other) | 定义按位右移位的行为:>> |
and(self, other) | 定义按位与操作的行为:& |
xor(self, other) | 定义按位异或操作的行为:^ |
or(self, other) | 定义按位或操作的行为:| |
反运算 | |
radd(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rsub(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rmul(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rtruediv(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rfloordiv(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rmod(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rdivmod(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rpow(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rlshift(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rrshift(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rand(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
rxor(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
ror(self, other) | (与上方相同,当左操作数不支持相应的操作时被调用) |
增量赋值运算 | |
iadd(self, other) | 定义赋值加法的行为:+= |
isub(self, other) | 定义赋值减法的行为:-= |
imul(self, other) | 定义赋值乘法的行为:*= |
itruediv(self, other) | 定义赋值真除法的行为:/= |
ifloordiv(self, other) | 定义赋值整数除法的行为://= |
imod(self, other) | 定义赋值取模算法的行为:%= |
ipow(self, other[, modulo]) | 定义赋值幂运算的行为:**= |
ilshift(self, other) | 定义赋值按位左移位的行为:<<= |
irshift(self, other) | 定义赋值按位右移位的行为:>>= |
iand(self, other) | 定义赋值按位与操作的行为:&= |
ixor(self, other) | 定义赋值按位异或操作的行为:^= |
ior(self, other) | 定义赋值按位或操作的行为:|= |
一元操作符 | |
pos(self) | 定义正号的行为:+x |
neg(self) | 定义负号的行为:-x |
abs(self) | 定义当被 abs() 调用时的行为 |
invert(self) | 定义按位求反的行为:~x |
类型转换 | |
complex(self) | 定义当被 complex() 调用时的行为(需要返回恰当的值) |
int(self) | 定义当被 int() 调用时的行为(需要返回恰当的值) |
float(self) | 定义当被 float() 调用时的行为(需要返回恰当的值) |
round(self[, n]) | 定义当被 round() 调用时的行为(需要返回恰当的值) |
index(self) | 1. 当对象是被应用在切片表达式中时,实现整形强制转换 2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 index 3. 如果 index 被定义,则 int 也需要被定义,且返回相同的值 |
上下文管理(with 语句) | |
enter(self) | 1. 定义当使用 with 语句时的初始化行为 2. enter 的返回值被 with 语句的目标或者 as 后的名字绑定 |
exit(self, exc_type, exc_value, traceback) | 1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么 2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作 |
容器类型 | |
len(self) | 定义当被 len() 调用时的行为(返回容器中元素的个数) |
getitem(self, key) | 定义获取容器中指定元素的行为,相当于 self[key] |
setitem(self, key, value) | 定义设置容器中指定元素的行为,相当于 self[key] = value |
delitem(self, key) | 定义删除容器中指定元素的行为,相当于 del self[key] |
iter(self) | 定义当迭代容器中的元素的行为 |
reversed(self) | 定义当被 reversed() 调用时的行为 |
contains(self, item) | 定义当使用成员测试运算符(in 或 not in)时的行为 |