2.1 python中函数和类也是对象,属于python的一等公民
class A(): def func(self): print(f'thie is A')def B(): print(f'this is B!')def print_type(i): print(type(i))
1. 函数可以赋值给一个变量
''''1.赋值给一个变量;'''obj_a = Aprint('1111')print(obj_a) # <class '__main__.A'># 带 ‘()’ 才是调用obj_a().func() # thie is Aobj_b = Bprint('2222')print(obj_b) # <function B at 0x7f800461ce18>obj_b() # this is B!
2. 可以添加到集合对象中
'''2.可以添加到集合对象中;'''obj_list = [A,B]print(obj_list) # [<class '__main__.A'>, <function B at 0x7fed4b596e18>]'''无return默认返回None'''for i in obj_list: print(i())#<__main__.A object at 0x7fed4b4eb240># this is B!# None
3. 可以作为参数传递给函数
'''3.可以作为参数传递给函数;'''for i in obj_list: print_type(i)# <class 'type'># <class 'function'>
'''4.可以做函数的返回值 装饰器 @decorator'''
def decorator_func():
print('444')
return B
tmp = decorator_func()
tmp() # this is B!
2.2 type object 和class的关系
object是一切的基类。type是元类

'''
# object是最顶层基类
# type也是一个类,同时type也是一个对象
'''
class Student:
pass
class MyStudent(Student):
pass
stu = Student()
a,b = 1,'abc'
print(type(a)) # <class 'int'>
print(type(b)) # <class 'str'>
print(type(int)) # <class 'type'>
print(type(str)) # <class 'type'>
# type -> int -> 1
# type -> class -> obj
print(type(stu)) # <class '__main__.Student'>
print(type(Student)) # <class 'type'>
print(int.__bases__) # (<class 'object'>,)
print(str.__bases__) # (<class 'object'>,)
print(Student.__bases__) # (<class 'object'>,)
print(MyStudent.__bases__) # (<class '__main__.Student'>,)
print(type.__bases__) # (<class 'object'>,)
print(object.__bases__) # ()
print(type(object)) # <class 'type'>
print(type(type)) # <class 'type'>
2.3 python中的常见内置类型
对象的三个特征 - > 身份id() 类型 值
None 全局只有一个
a = None
b = None
id(a)=93878928481072
id(b)=93878928481072
数值类型 int float complex bool
迭代类型
序列类型
映射类型 dict
集合 set frozenset
上下文管理类型 with
其他
- 模块类型
- class和实例
- 函数类型
- 方法类型
- 代码类型
- object对象
- type类型
- ellipsis类型
- notimplemented类型