Python中所有皆对象
本章节首先比照动态语言以及动静语言,而后介绍 python 中最底层也是面向对象最重要的几个概念-object、type和class之间的关系,以此来引出在python如何做到所有皆对象、随后列举python中的常见对象。
1.Python中所有皆对象
Python的面向对象更彻底,Java和C++中根底类型并不是对象。在Python中,函数和类也是对象,属于Python的一等公民。
对象
具备如下4个特色
- 1.赋值给一个变量
- 2.能够增加到汇合对象中
- 3.能够作为参数传递给函数
- 4.能够作为函数地返回值
上面从四个特色角度别离举例说明函数和类也是对象
1.1 类和函数都能够赋值给一个变量
类能够赋值给一个变量
class Person:
def __init__(self, name="lsg"):
print(name)
if __name__ == '__main__':
my_class = Person # 类赋值给一个变量
my_class() # 输入lsg,变量间接调用就能够实例化一个类,满足下面的特色1,这里显然阐明类也是一个对象
my_class("haha") # 输入haha
函数能够赋值给一个变量
def func_test(name='lsg'):
print(name)
if __name__ == '__main__':
my_func = func_test
my_func("haha") # 输入haha,对变量的操作就是对函数的操作,等效于对象的赋值,满足下面的特色1,阐明函数是对象。
1.2 类和函数都能够增加到汇合中
class Person:
def __init__(self, name="lsg"):
print(name)
def func_test(name='lsg'):
print(name)
if __name__ == '__main__':
obj_list = [func_test, Person]
print(obj_list) # 输入[<function func_test at 0x0000025856A2C1E0>, <class '__main__.Person'>]
1.3 类和函数都能够作为参数传递给函数
class Person:
def __init__(self, name="lsg"):
print(name)
def func_test(name='lsg'):
print(name)
def print_type(obj):
print(type(obj))
if __name__ == '__main__':
print_type(func_test)
print_type(Person)
输入如下
<class 'function'>
<class 'type'>
能够显著地看出类和函数都是对象
1.4 类和函数都能够作为函数地返回值
class Person:
def __init__(self, name="lsg"):
print(name)
def func_test(name='lsg'):
print(name)
def decorator_func():
print("pre function")
return func_test
def decorator_class():
print("pre class")
return Person
if __name__ == '__main__':
decorator_func()() # 返回的右值作为函数能够间接调用
decorator_class()() # 返回的右值作为类能够间接实例化
2.type、object和class的关系
代码举例如下, 能够得出三者的关系是type –> class –> obj
2.1 type –> int –> a
a = 1
print(type(a)) # <class 'int'>
print(type(int)) # <class 'type'>
2.2 type –> str –> b
b = 'abc'
print(type(b)) # <class 'str'>
print(type(str)) # <class 'type'>
2.3 type –> Student –> stu
class Student:
pass
stu = Student()
print(type(stu)) # <class '__main__.Student'>
print(type(Student)) # <class 'type'>
2.4 type –> list –> c
c = [1, 2]
print(type(c)) # <class 'list'>
print(type(list)) # <class 'type'>
总结图:
3.Python中常见的内置类型
对象的三个特色:身份、内存和值
-
身份:在内存中的地址,能够用
id(变量)
函数来查看 - 类型:任何变量都必须有类型
- 值
常见的内置类型如下
3.1 None:全局只有一个
如下代码,两个值为None的变量地址完全相同,可见None是全局惟一的
a = None
b = None
print(id(a))
print(id(b))
print(id(a) == id(b))
3.2 数值类型
- int
- float
- complex(复数)
- bool
3.3 迭代类型:iterator
3.4 序列类型
- list
- bytes、bytearray、memoryview(二进制序列)
- range
- tuple
- str
- array
3.5 映射类型(dict)
3.6 汇合
- set
- frozenset
3.7 上下文治理类型(with)
3.8 其余
- 模块类型
- class和实例
- 函数类型
- 办法类型
- 代码类型
- object类型
- type类型
- elipsis类型
- notimplemented类型
发表回复