文章目录
Python一切皆对象
1、对象
函数和类也是对象,属于Python的一等公民。
- 赋值给一个变量
- 可以添加到集合对象中
- 可以作为参数传递给函数
- 可以当作函数的返回值
def ask(name='hub'):
print(name)
class Person:
def __init__(self):
print('hubo')
"""
作为参数传递
"""
def print_type(item):
print(type(item))
print_type(Person)
"""
当作函数的返回值
"""
# def decorator_func():
# print('dec start')
# return ask
#
#
# my_ask = decorator_func()
# my_ask()
"""
添加到集合对象中
"""
# obj_list = list()
# obj_list.append(ask)
# obj_list.append(Person)
# for item in obj_list:
# print(item())
'''
可以赋值给一个变量
'''
# my_func = ask # 将函数对象赋值给变量
# my_func('hubo')
#
# my_class = Person # 将类对象赋值给变量
# my_class()
2、Type、Object 和 Class的关系
class本身也是一个对象由type生成。
type -> int -> 1
:type生成class,class生成object。
>>> a = 1
>>> type(1)
<class 'int'>
>>> type(int)
<class 'type'>
>>> int.__bases__
(<class 'object'>,)
object
是最顶层基类,所有类的最终父类都是object
,它的基类是空。
>>> object.__bases__
()
Type
:即是类又是对象,继承的类是Object
。
>>> type.__bases__
(<class 'object'>,)
Object
:是Type创建的对象。
>>> type(object)
<class 'type'>
>>> type(type)
<class 'type'>
由图可知道一切皆对象。
**注意:**object是Type的实例,所有的内置类都是由Type
创建出来的,Type创建了所有的对象。所以list
是一个类,又是Type
的对象。
Object
:是所有对象的基类,连Type
都要继承自它。Type
:创建了所有对象,Type
是自身的实例,所以一切都是对象。
3、常见内置类型
3.1、对象的三个特征
- 身份:对象在内存中的地址
- 类型:实例化对象的类型
- 值:
>>> a = 1
>>> id(a)
4410952368
>>> type(a)
<class 'int'>
>>> a
1
3.2、None(全局只有一个)
None类型,Python在解释器启动的时候用None类型生成一个None对象。
3.2、数值
- int
- float
- complex(复数)
- bool
3.3、迭代类型
可以用for循环来遍历,实现内置方法。
3.4、序列类型
- list
- bytes、bytearray、memoryview(二进制序列)
- range
- tuple
- str
- array
3.5、映射类型
dict:有key和map
3.6、集合
- set:
- frozenset:不可以修改的set
set和dict的实现原理相同,效率差不多。
3.7、上下文管理器(with)
实现两个方法:enter
和exit
。
3.8、其他类型
- 模块类型:form 和 import 也是类型。
- class和实例
- 函数类型
- 方法类型:是class里面定义的函数。
- 代码类型:代码会被Python解释器变为对象类型。
- object对象
- type类型
- ellipsis类型:省略号类型
- notimplemented类型: