内容来源于网络,本人只是在此稍作整理,如有涉及版权问题,归小甲鱼官方所有。
练习题(来自小甲鱼官方论坛)
0.对象相加(a + b),如果a对象有__ add__方法,请问b对象的__ radd__会被调用吗?
答:不会!
>>> class Nint(int):
def __radd__(self, other):
print("__radd__被调用了!")
return int.__add__(self, other)
>>> a = Nint(5)
>>> b = Nint(3)
>>> a + b
8
>>> 1 + b
__radd__被调用了!
4
1.Python什么时候会调用到反运算的魔法方法?
答:例如 a + b,如果a对象的__ add__方法没有实现或者不支持相应的操作,那么Python就会自动调用b的__ radd__方法。
2.请问如何在继承的类中调用基类的方法?
答:使用super()这个BIF函数。
class A(object):
def __init__(self, a=0):
self.a = a
def get(self):
return self.a
class B(A):
def __init__(self, b):
super(B, self).__init__(b)
def get(self):
return super(B, self).get()
if __name__ == '__main__':
b = B(10)
print(b.get())
3.如果我要继承的基类是动态的(有时候是A,有时候是B),我应该如何部署我的代码,以便基类可以随意修改。
答:你可以先为基类定义一个别名,在类定义的时候,使用别名代替你要继承的基类。因此,当你想要改变基类的时候,只需要修改别名赋值的那个语句即可。顺便说一下,当你的资源是视情况而定的时候,这个小技巧很管用。
BaseAlias = BaseClass # 为基类取别名
class Derived(BaseAlias):
def meth(self):
BaseAlias.meth(self) # 通过别名访问基类
...
4.尝试自己举一个例子说明如何使用类的静态属性。
答:类的静态属性很简单,在类中直接定义的变量(没有self.)就是静态属性。引用类的静态属性使用“类名.属性名”的形式。
类的静态属性应用(计算该类被实例化的次数):
#!/usr/bin/python
# -*- coding:utf-8 -*-
class C:
count = 0 # 静态属性
def __init__(self):
C.count = C.count + 1 # 类名.属性名的形式引用
def getCount(self):
return C.count
c1 = C()
c2 = C()
print(c1.getCount())
输出:
2
5.尝试自己列举说明如何使用类中的静态方法,并指出使用静态方法有什么不同和哪些需要注意的地方?
答:静态方法是类的特殊方法,静态方法只需要在普通方法的前边加上@staticmethod修饰符即可。
>>> class C:
@staticmethod
def static(arg1, arg2, arg3):
print(arg1, arg2, arg3, arg1 + arg2 + arg3)
def nostatic(self):
print("I'm the fucking normal method!")
>>> c = C()
>>> c.static(1, 2, 3)
1 2 3 6
>>> c.nostatic()
I'm the fucking normal method!
>>>
静态方法最大的优点是:不会绑定到实例对象上,换而言之就是节省开销。
>>> c1 = C()
>>> c2 = C()
>>> c1.static is C.static
True
>>> c1.nostatic is C.nostatic
False
>>> c1.static
<function C.static at 0x0000018650FA1E18>
>>> c2.static
<function C.static at 0x0000018650FA1E18>
>>> C.static
<function C.static at 0x0000018650FA1E18>
# 普通方法每个实例对象都拥有独立的一个,开销较大
>>> c1.nostatic
<bound method C.nostatic of <__main__.C object at 0x00000186518F9A20>>
>>> c2.nostatic
<bound method C.nostatic of <__main__.C object at 0x0000018651968DD8>>
>>> C.nostatic
<function C.nostatic at 0x000001865196B1E0>
使用的时候需要注意的地方:静态方法并不需要self参数,因此即使是使用对象去访问,self参数也不会传进去。
>>> c.static(1, 2, 3)
1 2 3 6
>>> C.static(1, 2, 3)
1 2 3 6
编程题
0.定义一个类,当实例化该类的时候,自动判断传入了多少个参数,并显示出来。
答:
>>> class C:
def __init__(self, *args):
if not args:
print("并没有传入参数")
else:
print("传入了%d个参数,分别是:" % len(args), end=' ')
for each in args:
print(each, end=' ')
>>> c = C(1, 2, 3)
传入了3个参数,分别是: 1 2 3
1.定义一个单词(Word)类继承自字符串,重写比较操作符,当两个Word类对象进行比较时,根据单词的长度来进行比较大小。
加分要求:实例化时如果传入的是带空格的字符串,则取第一个空格前的单词作为参数。
答:加分要求可以通过重载__ new__方法来实现(因为字符串是不可变类型),通过重写__ gt__、__ lt__、__ ge__、__ le__方法来定义Word类在比较操作中的表现。
注意:我们没有定义__ eq__和__ ne__方法。这是因为将会产生一些怪异不符合逻辑的结果(例如Word('FishC')会等于Word('Apple'))
代码如下:
class Word(str):
'''存储单词的类,定义比较单词的几种方法'''
def __new__(cls, word):
# 注意我们必须要用到__new__方法,因为str是不可变类型
# 所以我们必须在创建的时候将它初始化
if ' ' in word:
print("Value contains spaces. Truncating to first space.")
word = word[:word.index(' ')] # 单词是第一个空格之前的所有字符
return str.__new__(cls, word)
def __gt__(self, other):
return len(self) > len(other)
def __lt__(self, other):
return len(self) < len(other)
def __ge__(self, other):
return len(self) >= len(other)
def __le__(self, other):
return len(self) <= len(other)
w1 = Word('abcd')
w2 = Word('abca vsdv')
if w1 >= w2:
print(True)
输出:
Value contains spaces. Truncating to first space.
True
2.请写下这一节课你学习到的内容:格式不限,回忆并复述是加强记忆的好方式!
- 反运算相关的魔法方法
魔法方法 | 定义 |
---|---|
__ radd__(self, other) | 定义加法的行为:+(当左操作数不支持相应的操作时被调用) |
__ rsub__(self, other) | 定义减法的行为:-(当左操作数不支持相应的操作时被调用) |
__ rmul__(self, other) | 定义乘法的行为:*(当左操作数不支持相应的操作时被调用) |
__ rtruediv__(self, other) | 定义真除法的行为:/(当左操作数不支持相应的操作时被调用) |
__ rfloordiv__(self, other) | 定义整数除法的行为://(当左操作数不支持相应的操作时被调用) |
__ rmod__(self, other) | 定义取模算法的行为:%(当左操作数不支持相应的操作时被调用) |
__ rdivmod__(self, other) | 定义当被divmod()调用时的行为(当左操作数不支持相应的操作时被调用) |
__ rpow__(self, other) | 定义当被power()调用或**运算时的行为(当左操作数不支持相应的操作时被调用) |
__ 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) | 定义赋值幂运算的行为:**= |
__ ilshift__(self, other) | 定义赋值按位左移位的行为:<<= |
__ irshift__(self, other) | 定义赋值按位右移位的行为:>>= |
__ iand__(self, other) | 定义赋值按位与操作的行为:&= |
__ ixor__(self, other) | 定义赋值按位异或操作的行为:^= |
__ ior__(self, other) | 定义赋值按位或操作的行为:丨= |
- 一元操作符的魔法方法
魔法方法 | 定义 |
---|---|
__ neg__(self) | 定义正号的行为:+x |
__ pos__(self) | 定义负号的行为:-x |
__ abs__(self) | 定义当被abs()调用时的行为 |
__ invert__(self) | 定义按位求反的行为:~x |