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型別
歡迎關注我的公眾號查看更多文章

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/260862.html
標籤:Java
上一篇:云原生系列5 容器化日志之EFK
