写给编程高手的Python教程(09) 一切皆对象

413 阅读1分钟

写给编程高手的Python教程目录

函数和类是一等公民

在python中,任何事物都是对象,包括函数与类。首先看如下定义,ask函数与Person类。

def ask(name="bobby"):
    print(name)
class Person:
    def __init__(self):
        print("Person")
  • 函数和类可以赋值给一个变量
my_class = Person
my_class()
my_func = ask
my_func("bobby")
  • 函数和类可以作为元素存储在列表中
obj_list = []
obj_list.append(ask)
obj_list.append(Person)
for item in obj_list:
    item()
  • 函数和类可以作为其他函数的返回值和参数
def decorator_func():
    print("decorator start!")
    return ask

my_ask = decorator_func()
my_ask("tom...")

type、object和class之间的关系

python中的内置函数type、可以获取对象的类型。

a = 1
b = "abc"
print(type(a))  #int类
print(type(b)) #str类

python中int、str等类型的type值为type,也就是说它们都是type的实例

print(type(int)) #type类
print(type(str)) #type类

class Student:
    pass
stu = Student()
print(type(stu)) #Student类
print(type(Student)) #type类

在python中, type是一个类,同时也是一个对象。type对象是type类的一个实例,type类的父类为object。

print(type(type)) #type类
print(type.__bases__) #object类

object类是type类的一个实例,object类的父类为空。

print(type(object)) #type类
print(object.__bases__) #空

对象的三个特征

  • 身份 (地址),python中的id函数可以获取到对象地址
a = 1
print(id(a))
  • 类型,python中的type函数可以获取到对象类型

None(全局只有一个)

a = None
b = None
print(id(a) == id(b))