在?Python 中一切都是對象。如果要在?Python 中表示一個對象,除了定義?class 外還有哪些方式呢?我們今天就來盤點一下。
0x00 dict
字典或映射存儲?KV 鍵值對,它對查找、插入和刪除操作都有比較高效率。用一個?dict 對象可以非常容易的表示一個對象。?dict 的使用也?很靈活,可以修改、添加或刪除屬性。
>>> student={ 'name':'jack', 'age':18, 'height':170 } >>> student {'name': 'jack', 'age': 18, 'height': 170} # 查看屬性 >>> student['name'] 'jack' # 添加屬性 >>> student['score']=89.0 >>> student {'name': 'jack', 'age': 18, 'height': 170, 'score': 89.0} # 刪除屬性 >>> del student['height'] >>> student {'name': 'jack', 'age': 18, 'score': 89.0}
0x01 tuple
tuple 也可以表示一個對象,相對于?dict 來說,?它是不可變的,一旦創(chuàng)建就不能隨意修改。 tuple 也只能通過下標來訪問對象的屬性,因此當屬性比較多時使用起來沒有?dict 方便。
# 對象屬性為name、age、height >>> student=('jack',18,170.0) >>> student ('jack', 18, 170.0) >>> student[1] 18 # tuple不能修改 >>> student[2]=175.0 TypeError: 'tuple' object does not support item assignment
0x02 collections.namedtuple
顧名思義?namedtuple 就是命名元組。它是?tuple 數(shù)據(jù)類型的擴展,同樣地一旦創(chuàng)建,它的元素也是不可變的。與普通元組相比命名元組可以通過“屬性名”來訪問元素。
>>> from collections import namedtuple >>> Point = namedtuple('Point','x,y,z') >>> p = Point(1,3,5) >>> p Point(x=1, y=3, z=5) >>> Point = namedtuple('Point','x y z') >>> p = Point(1,3,5) >>> p Point(x=1, y=3, z=5) >>> p.x 1 >>> p.y = 3.5 AttributeError: can't set attribute # 可以看出通過namedtuple定義對象,就是一個class類型的 >>> type(p)
對于一個簡單的對象,我們使用?namedtuple 很方便的來定義,它比定義一個普通?class 要有更好的空間性能。
0x03 type.NamedTuple
Python3.6 中新增了?type.NamedTuple 類,它與?collections.namedtuple 的操作是類似的。不過,要定義?NamedTuple 就稍微不一樣了。
>>> from typing import NamedTuple # 定義Car類,繼承于NamedTuple,并定義屬性color、speed、autmatic >>> class Car(NamedTuple): color:str speed:float automatic:bool >>> car = Car('red',120.0,True) >>> car Car(color='red', speed=120.0, automatic=True) >>> type(car)# tuple都是不可變的 >>> car.speed = 130.0 AttributeError: can't set attribute
0x04 types.SimpleNamespace
使用?SimpleNamespace 也可以很方便的定義對象。它的定義等價于
class SimpleNamespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __repr__(self): keys = sorted(self.__dict__) items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys) return "{}({})".format(type(self).__name__, ", ".join(items)) def __eq__(self, other): return self.__dict__ == other.__dict__
例如定義一個?Car 對象
>>> car = SimpleNamespace(color='blue',speed=150.5,automatic=True) >>> car namespace(automatic=True, color='blue', speed=150.5) >>> car.color 'blue' >>> car.speed = 120 >>> car namespace(automatic=True, color='blue', speed=120) # 動態(tài)添加屬性 >>> car.shift = 23 >>> car namespace(automatic=True, color='blue', shift=23, speed=120) # 刪除屬性 >>> del car.shift >>> car namespace(automatic=True, color='blue', speed=120)
0x05 struct.Struct
這是一個結構體對象,可以把?C 語言中的?struct 序列化成?Python 對象。例如處理文件中的二進制數(shù)據(jù)或從網(wǎng)絡中請求的數(shù)據(jù),可以使用這個?struct.Struct 來表示。
使用?struct 好處是數(shù)據(jù)格式是預先定義好的,可以對數(shù)據(jù)進行打包成二進制數(shù)據(jù),空間效率會好很多。
# 定義一個struct,'1sif'表示數(shù)據(jù)的格式,1s一個字符長度,i表示整數(shù),f表示浮點數(shù) >>> Student=Struct('1sif') # 使用pack方法打包數(shù)據(jù),存儲性別、年齡、身高 >>> stu = Student.pack(b'm',18,175.0) >>> stu b'm\x00\x00\x00\x12\x00\x00\x00\x00\x00/C' # unpack方法解包 >>> Student.unpack(stu) (b'm', 18, 175.0)
0x06 class
class 當然是定義一個對象的標準方式了。在?Python 定義類也非常簡單,除了可以定義屬性還可以定義方法。
>>> class Student: def __init__(self,name,age,height): self.name = name self.age = age self.height = height def printAge(self): print(self.age) >>> stu = Student('jack',18,175.0) # 如果想讓定義的對象輸出屬性信息可以重寫__repr__方法 >>> stu <__main__.Student object at 0x10afcd9b0> >>> stu.name 'jack' >>> stu.age = 19
0x07 總結一下
本文盤點?Python 中定義對象各種的方法,除了?class ,還有有?dict 、?tuple 、?namedtuple 、?NamedTuple 、?SimpleNamespace 和?Struct 。
如果一個對象屬性不多可以使用?tuple ;
如果一個對象屬性不可變可以考慮使用?namedtuple 或?NamedTuple ;
如果一個對象要轉成?JSON 進行傳輸可以使用?dict ;
如果考慮比較空間性能,可以使用?Struct 。
總結
以上所述是小編給大家介紹的在Python中表示一個對象的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
