第一课 python进阶一切皆对象和魔法函数
tags:
- Docker
- 慕课网
categories:
- 一切皆对象
- 魔法函数
文章目录
第一节 一切皆对象
1.1 python中一切皆对象
- python中函数和类也是对象,属于python的一等公民。这在java和C++中并不是这样的。python中代码和模块其实也是对象。
- 如果类本身是对象,那它如何实例化实例对象呢?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的关系
- type的两种用法:
- 用来生成类,平时我们常见的int, string,类这种对象都是由类对象type生成的。
- 返回对象的类型
- 查看基类,类.bases。object是最顶层的基类,object的基类输出为空。看父亲
- 这里要注意: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中常见的内置类型
- 对象的三个特征:身份(地址id)、类型(type)、值
- None类型全局只有一个。
a = None
b = None
print(id(a) == id(b))
- 数值类型:int、float、complex(复数)、bool
- 迭代类型:迭代器、生成器(后面有讲)
- 序列类型: list、bytes、bytearray、memoryview(二进制序列)
- 映射:字典dict
- 集合:set、fronzenset
- 上下文管理类型:with语句
- 其他:模块类型、class和实例、函数类型、方法类型、代码类型、object对象、type类型、ellipsis类型、notimplemented类对象。
第二节 魔法函数
2.1 魔法函数介绍
- 魔法函数增强对象的属性。
- 使用python帮我们定义的魔法函数
- 例子:for循环会拿到对象的迭代器,但是Company没有迭代器。解释器自动优化,它就会一次次调用__getitem__函数。
- 对象的迭代器通过__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
-
安装ipython和notebook
- pip install -i https://pypi.douban.com/simple ipython
- pip install -i https://pypi.douban.com/simple notebook
- ipython notebook命令启动
-
__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
- __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
- len()函数在python中,对一些内置类型list,set,dict进行长度计算时o(1)。是非常高效的,它会去走一些捷径,用c实现的。
- 所以我们尽量使用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))
2257

被折叠的 条评论
为什么被折叠?



