在Python中表示一個(gè)對(duì)象的方法
在 Python 中一切都是對(duì)象。如果要在 Python 中表示一個(gè)對(duì)象,除了定義 class 外還有哪些方式呢?我們今天就來盤點(diǎn)一下。
0x00 dict
字典或映射存儲(chǔ) KV 鍵值對(duì),它對(duì)查找、插入和刪除操作都有比較高效率。用一個(gè) dict 對(duì)象可以非常容易的表示一個(gè)對(duì)象。 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 也可以表示一個(gè)對(duì)象,相對(duì)于 dict 來說, 它是不可變的,一旦創(chuàng)建就不能隨意修改。 tuple 也只能通過下標(biāo)來訪問對(duì)象的屬性,因此當(dāng)屬性比較多時(shí)使用起來沒有 dict 方便。
# 對(duì)象屬性為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ù)類型的擴(kuò)展,同樣地一旦創(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定義對(duì)象,就是一個(gè)class類型的
>>> type(p)
<class '__main__.Point'>
對(duì)于一個(gè)簡單的對(duì)象,我們使用 namedtuple 很方便的來定義,它比定義一個(gè)普通 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)
<class '__main__.Car'>
# tuple都是不可變的
>>> car.speed = 130.0
AttributeError: can't set attribute
0x04 types.SimpleNamespace
使用 SimpleNamespace 也可以很方便的定義對(duì)象。它的定義等價(jià)于
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__
例如定義一個(gè) Car 對(duì)象
>>> 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) # 動(dòng)態(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
這是一個(gè)結(jié)構(gòu)體對(duì)象,可以把 C 語言中的 struct 序列化成 Python 對(duì)象。例如處理文件中的二進(jìn)制數(shù)據(jù)或從網(wǎng)絡(luò)中請(qǐng)求的數(shù)據(jù),可以使用這個(gè) struct.Struct 來表示。
使用 struct 好處是數(shù)據(jù)格式是預(yù)先定義好的,可以對(duì)數(shù)據(jù)進(jìn)行打包成二進(jìn)制數(shù)據(jù),空間效率會(huì)好很多。
# 定義一個(gè)struct,'1sif'表示數(shù)據(jù)的格式,1s一個(gè)字符長度,i表示整數(shù),f表示浮點(diǎn)數(shù)
>>> Student=Struct('1sif')
# 使用pack方法打包數(shù)據(jù),存儲(chǔ)性別、年齡、身高
>>> 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 當(dāng)然是定義一個(gè)對(duì)象的標(biāo)準(zhǔn)方式了。在 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)
# 如果想讓定義的對(duì)象輸出屬性信息可以重寫__repr__方法
>>> stu
<__main__.Student object at 0x10afcd9b0>
>>> stu.name
'jack'
>>> stu.age = 19
0x07 總結(jié)一下
本文盤點(diǎn) Python 中定義對(duì)象各種的方法,除了 class ,還有有 dict 、 tuple 、 namedtuple 、 NamedTuple 、 SimpleNamespace 和 Struct 。
如果一個(gè)對(duì)象屬性不多可以使用 tuple ;
如果一個(gè)對(duì)象屬性不可變可以考慮使用 namedtuple 或 NamedTuple ;
如果一個(gè)對(duì)象要轉(zhuǎn)成 JSON 進(jìn)行傳輸可以使用 dict ;
如果考慮比較空間性能,可以使用 Struct 。
總結(jié)
以上所述是小編給大家介紹的在Python中表示一個(gè)對(duì)象的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
Python連接Hadoop數(shù)據(jù)中遇到的各種坑(匯總)
這篇文章主要介紹了Python連接Hadoop數(shù)據(jù)中遇到的各種坑,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Django contenttypes 框架詳解(小結(jié))
這篇文章主要介紹了Django contenttypes 框架詳解(小結(jié)),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08
Python程序中用csv模塊來操作csv文件的基本使用教程
這篇文章主要介紹了Python程序中用csv模塊來操作csv文件的基本使用教程,csv文件中也是格式化的數(shù)據(jù),只不過csv本身沒有XML和JSON那么流行...需要的朋友可以參考下2016-03-03
淺談python3打包與拆包在函數(shù)的應(yīng)用詳解
這篇文章主要介紹了淺談python3打包與拆包在函數(shù)的應(yīng)用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
python代碼 if not x: 和 if x is not None: 和 if not x is None:使用
這篇文章主要介紹了python代碼 if not x: 和 if x is not None: 和 if not x is None:使用介紹,需要的朋友可以參考下2016-09-09
Python生成ubuntu apt鏡像地址實(shí)現(xiàn)
本文主要介紹了Python生成ubuntu apt鏡像地址實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05

