魔法方法
魔法方法总是被双下划线包围,例如__init__。
魔法方法的第一个参数应为cls(类方法) 或者self(实例方法)。
*cls:代表一个类的名称
*self:代表一个实例对象的名称
1.基本的魔法方法
init(self[, …]) 构造器,当一个实例被创建的时候调用的初始化方法
【例子】
class Rectangle:
def __init__(self, x, y):
self.x = x
self.y = y
def getArea(self):'''计算矩形面积'''
return self.x * self.y
rect = Rectangle(4, 5)
print(rect.getArea()) # 20
2.算数运算符
add(self, other)定义加法的行为:+
sub(self, other)定义减法的行为:-
class MyClass:
def __init__(self, height, weight):
self.height = height
self.weight = weight
'''两个对象的长相加,宽不变.返回一个新的类'''
def __add__(self, others):
return MyClass(self.height + others.height, self.weight + others.weight)
'''两个对象的宽相减,长不变.返回一个新的类'''
def __sub__(self, others):
return MyClass(self.height - others.height, self.weight - others.weight)
'''说一下自己的参数'''
def intro(self):
print("高为", self.height, " 重为", self.weight)
def main():
a = MyClass(height=10, weight=5)
a.intro()
b = MyClass(height=20, weight=10)
b.intro()
c = b - a
c.intro()
d = a + b
d.intro()
if __name__ == '__main__':
main()
''' 高为 10 重为 5
高为 20 重为 10
高为 10 重为 5
高为 30 重为 15'''
3.迭代器
迭代是 Python 最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。
迭代器只能往前不会后退。
字符串,列表或元组对象都可用于创建迭代器。
links = {'B': '百度', 'A': '阿里', 'T': '腾讯'}
for each in links:
print('%s -> %s' % (each, links[each]))
'''
B -> 百度
A -> 阿里
T -> 腾讯
'''
for each in iter(links):
print('%s -> %s' % (each, links[each]))
'''
B -> 百度
A -> 阿里
T -> 腾讯
'''
4.生成器
在 Python 中,使用了 yield 的函数被称为生成器
【例子】用生成器实现斐波那契数列。
def libs(n):
a = 0
b = 1
while True:
a, b = b, a + b
if a > n:
return
yield a
for each in libs(100):
print(each, end=' ')
''' 1 1 2 3 5 8 13 21 34 55 89'''