溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在Python中表示一個對象

發(fā)布時間:2021-05-20 17:28:19 來源:億速云 閱讀:156 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)如何在Python中表示一個對象,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

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)
<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 也可以很方便的定義對象。它的定義等價于

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

這是一個結(jié)構(gòu)體對象,可以把 C 語言中的 struct 序列化成 Python 對象。例如處理文件中的二進制數(shù)據(jù)或從網(wǎng)絡(luò)中請求的數(shù)據(jù),可以使用這個 struct.Struct 來表示。

使用 struct 好處是數(shù)據(jù)格式是預(yù)先定義好的,可以對數(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

python有哪些常用庫

python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

關(guān)于如何在Python中表示一個對象就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI