Python面向对象上

1. 迭代器 iterator

  • 可迭代对象 iterable
  • 迭代器是在定了 __next__ 和 __iter__ 方法的类
  • 调用 __next__ 和 __iter__都不带任何其他的参数
class TestIterator:
    value = 0
    def __next__(self):
        self.value += 1
        if self.value > 10: raise StopIteration
        return self.value
    def __iter__(self):
        return self
  • 可迭代对象不一定是迭代器, 迭代器一定是可迭代对象
  • 可迭代对象: sequence (list, dict, tuple), strings, iterator,
  • More formally, an object that implements the __iter__ method is iterable, and the object
    implementing __next__ is the iterator
  • Make sequence from Iterators, for example, convert an iterator to a list using the list constructor.
ti = TestIterator()
print(list(ti))

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  • 迭代器, 使用一次就不能使用了
    • 去一次就不能使用了
    • 会记住你上一次停留的位置
  • convert a list to a iterator by using the iter() function.
list1 = [1, 2, 3, 4, 5]
it = iter()
print(it)

Output:
<list_iterator object at 0x032BE4F0>

2.面向对象

  • 面向过程

    • 面向过程指将我们的程序分解为一个一个步骤,通过对每个步骤的抽象 来完成程序
    • 这种编写方式往往只适用于一个功能, 如果要实现别的功能,往往复用性比较低
    • 这种编程方式符合人类的思维,编写起来比较容易
  • 面向对象

    • 面向对象语言, 关注的是对象,而不注重过程。 一切皆对象
    • 这种编码方式比较容易阅读, 并且易于维护,容易复用。但是编写的过程中不太符合长队的思维,编写相对麻烦。

3. 类 class

  • 类的创建
class MyClass()
    pass

–大驼峰明明规则

  • 实列的创建
mc = MyClass()
  • 类就是包含了属性和方法的对象
  • 需要访问&调用类的属性&对象, mc.variable & mc.method()

4. 属性和方法

  • 属性: 定义在类中的数据 & 变量
  • 方法:类中定义的函数就叫方法。
    –定义方法时, 至少要传递一个参数。 这个传递的参数就是self
  • 类和类的实例都是内存中的一块区域。mc.name = “Jack” 是修改实例 mc的name属性;MyClass.name = 'Jack Ma’是修改类的name属性。
  • MyClass 中的所有的属性&方法都可以被实例继承
  • 一切皆是对象。
    • 比如, 把蛋糕放到冰箱里面并关上冰箱。冰箱就是一个对象
    • 蛋糕是冰箱中的一个属性
    • 打冰箱是method1, 关上冰箱是method2

5. self参数

  • self 参数
    • self 参数指class 本身,
    • isinstance(self, class) == True
    • 定义方法, 必须要传self参数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值