【Python核心編程筆記】1、Python中一切皆對象

Python中一切皆對象

本章節首先對比靜態語言以及動態語言,而後介紹 python 中最底層也是面向對象最重要的幾個概念-object、type和class之間的關係,以此來引出在python如何作到一切皆對象、隨後列舉python中的常見對象。

1.Python中一切皆對象

Python的面向對象更完全,Java和C++中基礎類型並非對象。在Python中,函數和類也是對象,屬於Python的一等公民。 對象具備以下4個特徵
  • 1.賦值給一個變量
  • 2.能夠添加到集合對象中
  • 3.能夠做爲參數傳遞給函數
  • 4.能夠做爲函數地返回值

下面從四個特徵角度分別舉例說明函數和類也是對象python

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

能夠明顯地看出類和函數都是對象spa

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 --> objcode

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

總結圖:
image.png對象

3.Python中常見的內置類型

對象的三個特徵:身份、內存和值
  • 身份:在內存中的地址,能夠用id(變量)函數來查看blog

  • 類型:任何變量都必須有類型

常見的內置類型以下ip

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類型
相關文章
相關標籤/搜索