How to represent an object in Python

About
program ape a thoughtful, lifelong learning practitioners, is currently in a start-up team any team lead, technology stack involves Android, Python, Java, and Go, this is the main technology stack our team.
GitHub: https://github.com/hylinux1024
micro-channel public number: Lifetime developer (angrycode)

In Pythoneverything is an object. If you want to Pythonrepresent an object in addition to defining the classoutside what other way? To take stock of what we have today.

0x00 dict

Dictionaries or mapping memory KVkey-value pairs, it has to find, insert and delete operations have relatively high efficiency. With a dicttarget it can be very easy to represent an object. dictThe use is also very flexible, you can modify, add, or delete attributes.

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

tupleMay also represent an object in relation to dictit, it is immutable, once created can not be arbitrarily modified. tupleOnly property to access the object by index, so when the property relatively long time to use not dicteasy.

# 对象属性为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

As the name suggests namedtupleis named tuple. It is the tupledata type of extension, in the same manner once created, its elements are immutable. Compared with ordinary tuple named tuple elements can be accessed through the "property name."

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

For a simple object, we use namedtuplevery easy to define, it is a common ratio is defined classto have a better performance space.

0x03 type.NamedTuple

Python3.6He added a type.NamedTupleclass, and its collections.namedtupleoperation is similar. However, to define NamedTupleit a little different.

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

Use SimpleNamespacecan also be easily defined objects. Its definition is equivalent to

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__

For example a definition of Caran object

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

This is a structure object can Clanguage structserialize Pythonobjects. Such as processing or binary data file requested data from the network, this may be used struct.Structto represent.

Use structbenefit is that data is pre-defined format, the data can be packed into binary data, space efficiency will be much better.

# 定义一个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

classOf course, the object is to define a standard way of. In Pythonthe definition of the class is also very simple, in addition to the method defined attributes may also be defined.

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

This article inventory Pythonobjects defined in a variety of methods, in addition class, there was the dict, tuple, namedtuple, NamedTuple, SimpleNamespaceand Struct.
If a small object properties may be used tuple;
if an immutable object property may consider namedtupleor NamedTuple;
if you want to turn into an object JSONfor transmission may be used dict;
consideration of performance comparison space, may be used Struct.

0x08 learning materials

  • Python Tricks: A Buffet of Awesome Python Features
    ——Dan Bader

Guess you like

Origin www.cnblogs.com/angrycode/p/11431431.html