第一课 python进阶一切皆对象和魔法函数

第一课 python进阶一切皆对象和魔法函数

tags:

  • Docker
  • 慕课网

categories:

  • 一切皆对象
  • 魔法函数

第一节 一切皆对象

1.1 python中一切皆对象

  1. python中函数和类也是对象,属于python的一等公民。这在java和C++中并不是这样的。python中代码和模块其实也是对象。
  2. 如果类本身是对象,那它如何实例化实例对象呢?python中的类可以理解成为一个模板对象,它可以根据模板对象生成一个对象。
    在这里插入图片描述
def ask(name="bobby"):
    print(name)


class Person:
    def __init__(self):
        print("bobby")


# 1. 这里把类和函数直接复制给一个变量
my_func = ask
my_func("Sam")
my_class = Person
my_class()
# 2. 可以把对象添加到集合中
obj_list = [ask, Person]
for item in obj_list:
    print(item())


# 3. 可以作为参数传递给函数
def print_type(item):
    print(type(item))


# 4. 可以当做函数的返回值
def decorator_func():
    print("dec start")
    return ask


if "__name__" == "__main__":
    print_type(Person)
    my_ask = decorator_func()
    my_ask()

1.2 type、object和class的关系

  1. type的两种用法:
    • 用来生成类,平时我们常见的int, string,类这种对象都是由类对象type生成的。
    • 返回对象的类型
  2. 查看基类,类.basesobject是最顶层的基类,object的基类输出为空。看父亲
  3. 这里要注意:type也是一个类,同时它也是一个自己的对象,下面它们互相指向对方。看实例
>>> type.__bases__
(<class 'object'>,)
>>> type(object)
<class 'type'>
>>> object.__bases__
()

在这里插入图片描述

a = 1
b = "abc"
# 这里可以知道:type->int->1
print(type(1))
print(type(int))
print(type(b))
print(type(str))


class Student:
    pass


class MyStudent(Student):
    pass


stu = Student()
print(type(stu))
print(type(Student))
# 查看基类__bases__
print(int.__bases__)
print(str.__bases__)
print(Student.__bases__)
print(MyStudent.__bases__)

print(type.__bases__)
print(object.__bases__)
print(type(object))

1.3 python中常见的内置类型

  1. 对象的三个特征:身份(地址id)、类型(type)、值
  2. None类型全局只有一个。
a = None
b = None
print(id(a) == id(b))
  1. 数值类型:int、float、complex(复数)、bool
  2. 迭代类型:迭代器、生成器(后面有讲)
  3. 序列类型: list、bytes、bytearray、memoryview(二进制序列)
  4. 映射:字典dict
  5. 集合:set、fronzenset
  6. 上下文管理类型:with语句
  7. 其他:模块类型、class和实例、函数类型、方法类型、代码类型、object对象、type类型、ellipsis类型、notimplemented类对象。

第二节 魔法函数

2.1 魔法函数介绍

  1. 魔法函数增强对象的属性。
  2. 使用python帮我们定义的魔法函数
  3. 例子:for循环会拿到对象的迭代器,但是Company没有迭代器。解释器自动优化,它就会一次次调用__getitem__函数
  4. 对象的迭代器通过__iter__魔法函数实现
class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __getitem__(self, item):
        return self.employee[item]

company = Company(["tom", "bob", "jane"])
# 这里因为魔法方法__getitem__ 它可以使对象变成一个可迭代的对象
for em in company:
    print(em)

2.2 魔法函数一览

作用魔法方法
字符串表示__repr__、__str__
集合、序列相关__len__、__getitem__、__setitem__、__delitem__、__contains__
迭代相关__iter__、__next__
可调用__call__
with上下文管理器__enter__、__exit__
数值转换__abs__、__bool__、__int__、__float__、__hash__、__index__
元类相关__init__、__new__
属性相关__getattr__、__setattr__、__getattribute__、__setattribute__ 、__dir__
属性描述符__get__、__set__、__delete__
协程__await__、__aiter__、__anext__、__aenter__ 、__aexit__
数学运算比较多自己查比如:__abs__、__lt__、__gt__

2.3 魔法函数repr、str

  1. 安装ipython和notebook

    • pip install -i https://pypi.douban.com/simple ipython
    • pip install -i https://pypi.douban.com/simple notebook
    • ipython notebook命令启动
  2. __str__ 对我们的对象字符串格式化使用的

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __str__(self):
        return ",".join(self.employee)
    
company = Company(["tom", "bob", "jane"])
company # <__main__.Company at 0x15a8c8d7b70>
print(company) # tom,bob,jane
  1. __repr__ 开发模式下调用的
class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __repr__(self):
        return ",".join(self.employee)
    
company = Company(["tom", "bob", "jane"])
company # tom,bob,jane 调试模式下
print(company) # tom,bob,jane

2.4 魔法函数len

  1. len()函数在python中,对一些内置类型list,set,dict进行长度计算时o(1)。是非常高效的,它会去走一些捷径,用c实现的。
  2. 所以我们尽量使用python内部的函数,效率会比较高。
class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __len__(self):
        return len(self.employee)


company = Company(["tom", "bob", "jane"])
print(len(company))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值