if __name__ == '__main__': sup = Superhero(name="Tick")
# 通过isinstance方法,可以判断,实例和类的关系 if isinstance(sup, Human): print('I am human') # 通过type(instance)可以得到实例的class对象 if type(sup) is Superhero: print('I am a superhero')
# 调用子类独有的方法 sup.boast() # => I wield the power of super strength! # => I wield the power of bulletproofing!
# 继承了的类属性 sup.age = 31 print(sup.age) # => 31
# 子类独有的属性 print('Am I Oscar eligible? ' + str(sup.movie))
I am human
I am a superhero
(<class '__main__.Superhero'>, <class '__main__.Human'>, <class 'object'>)
Superhuman
Dun, dun, DUN!
Tick: Spoon
I wield the power of super strength!
I wield the power of bulletproofing!
31
Am I Oscar eligible? False
# 调用覆盖后的方法 print(sup.sing()) # => nan nan nan nan nan batman!
# 两个父类有重名方法时,顺序在前的优先级更高 sup.say('I agree') # => Sad Affleck: I agree
# 调用第二父类方法 print(sup.sonar()) # => ))) ... (((
# 继承类属性 sup.age = 100 print(sup.age) # => 100
# 输出从第二父类继承的属性,该属性已被覆盖 print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
(<class '__main__.Batman'>, <class '__main__.Superhero'>, <class '__main__.Human'>, <class '__main__.Bat'>, <class 'object'>)
Superhuman
nan nan nan nan nan batman!
Sad Affleck: I agree
))) ... (((
100
Can I fly? False
# 生成器可以帮你偷很多懒 defdouble_numbers(iterable): for i in iterable: yield i + i
1 2 3 4 5 6 7 8 9
# 生成器可以节省很多内存 # 因为它们只加载所需处理iterable中的下一个值的数据(边生成边处理) # 普通方法需要 先生成后处理 # 这使其可以进行大范围的数据操作(其他方法可能不行) # 注意:python 3中,“range”替换了“xrange” for i in double_numbers(range(1, 900000000)): # `range` is a generator. print(i) if i >= 30: break
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
1 2 3 4 5 6
# 正如可以创建列表理解一样,也可以创建生成器理解 # 这里,圆括号是关键,你以为是tuples,实际上是生成器 values = (-x for x in [1,2,3,4,5]) print(values) for x in values: print(x) # prints -1 -2 -3 -4 -5 to console/terminal
<generator object <genexpr> at 0x102e9c990>
-1
-2
-3
-4
-5
1 2 3 4
# 也可以直接把一个生成器理解投射到list上 values = (-x for x in [1,2,3,4,5]) gen_to_list = list(values) print(gen_to_list) # => [-1, -2, -3, -4, -5]