如何在Python中表示一個對象

關於我
編程界的一名小小程序猿,目前在一個創業團隊任team lead,技術棧涉及Android、Python、Java和Go,這個也是咱們團隊的主要技術棧。 聯繫:hylinux1024@gmail.comlinux

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來講,它是不可變的,一旦建立就不能隨意修改。tuple也只能經過下標來訪問對象的屬性,所以當屬性比較多時使用起來沒有dict方便。bash

# 對象屬性爲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數據類型的擴展,一樣地一旦建立,它的元素也是不可變的。與普通元組相比命名元組能夠經過「屬性名」來訪問元素。網絡

>>> 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) <class '__main__.Point'> 複製代碼

對於一個簡單的對象,咱們使用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)
<class '__main__.Car'>
# tuple都是不可變的
>>> car.speed = 130.0
AttributeError: can't set attribute 複製代碼

0x04 types.SimpleNamespace

使用SimpleNamespace也能夠很方便的定義對象。它的定義等價於ui

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對象spa

>>> 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)
# 動態添加屬性
>>> 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對象。例如處理文件中的二進制數據或從網絡中請求的數據,可使用這個struct.Struct來表示。code

使用struct好處是數據格式是預先定義好的,能夠對數據進行打包成二進制數據,空間效率會好不少。

# 定義一個struct,'1sif'表示數據的格式,1s一個字符長度,i表示整數,f表示浮點數
>>> Student=Struct('1sif')
# 使用pack方法打包數據,存儲性別、年齡、身高
>>> 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,還有有dicttuplenamedtupleNamedTupleSimpleNamespaceStruct
若是一個對象屬性很少可使用tuple;
若是一個對象屬性不可變能夠考慮使用namedtupleNamedTuple
若是一個對象要轉成JSON進行傳輸可使用dict;
若是考慮比較空間性能,可使用Struct

0x08 學習資料

  • Python Tricks: A Buffet of Awesome Python Features ——Dan Bader
相關文章
相關標籤/搜索