2.1 python中函数和类也是对象,属于python的一等公民

  1. class A():
  2. def func(self):
  3. print(f'thie is A')
  4. def B():
  5. print(f'this is B!')
  6. def print_type(i):
  7. print(type(i))

1. 函数可以赋值给一个变量

  1. ''''1.赋值给一个变量;'''
  2. obj_a = A
  3. print('1111')
  4. print(obj_a) # <class '__main__.A'>
  5. # 带 ‘()’ 才是调用
  6. obj_a().func() # thie is A
  7. obj_b = B
  8. print('2222')
  9. print(obj_b) # <function B at 0x7f800461ce18>
  10. obj_b() # this is B!

2. 可以添加到集合对象中

  1. '''2.可以添加到集合对象中;'''
  2. obj_list = [A,B]
  3. print(obj_list) # [<class '__main__.A'>, <function B at 0x7fed4b596e18>]
  4. '''无return默认返回None'''
  5. for i in obj_list:
  6. print(i())
  7. #<__main__.A object at 0x7fed4b4eb240>
  8. # this is B!
  9. # None

3. 可以作为参数传递给函数

  1. '''3.可以作为参数传递给函数;'''
  2. for i in obj_list:
  3. print_type(i)
  4. # <class 'type'>
  5. # <class 'function'>

4. 可以做函数的返回值 装饰器原理 @decorator

'''4.可以做函数的返回值 装饰器 @decorator'''
def decorator_func():
    print('444')
    return B
tmp = decorator_func()
tmp()   # this is B!

2.2 type object 和class的关系

object是一切的基类。type是元类

2 python中一切皆对象 - 图1

'''
# 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

其他

  1. 模块类型
  2. class和实例
  3. 函数类型
  4. 方法类型
  5. 代码类型
  6. object对象
  7. type类型
  8. ellipsis类型
  9. notimplemented类型