python - 编写 Python POO。棉花糖或原生 Python。创建类的最佳方式是什么?

标签 python class marshmallow

在使用 Python 编程时,我发现了棉花糖。我总是在 native python 上创建类。这个库(或另一个库)是创建基于 POO 的程序的最佳方法吗?

import datetime as dt

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = dt.datetime.now()

    def __repr__(self):
        return '<User(name={self.name!r})>'.format(self=self)


from marshmallow import Schema, fields

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()

最佳答案

Marshmallow如果您需要序列化/反序列化,则非常有用。这与 OOP 无关。

如果您喜欢属性的声明和键入方式,您可能会对 dataclasses 感兴趣。 Python 3.7 中引入的功能。

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

关于python - 编写 Python POO。棉花糖或原生 Python。创建类的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54559971/

相关文章:

python - 如何从一列中的所有数字中删除\xa3?

python - 无法使用 BS4 从表格中仅提取可见文本

php - 类方法调用前 Hook

c++ - 如何在类中存储常量数组?

sqlalchemy - 如何将 marshmallow-sqlalchemy 与异步代码一起使用?

python - 用 `data_key` 定义的 Marshmallow 字段和用 `attribute` 定义的 Marshmallow 字段有什么区别(标识符相反?)

python - 基于FFT的音频分类

python - TypeError : a bytes-like object is required, not 'str' when writing to a file

python - 从两侧实现 __rmul__,python

python - flask 棉花糖/SqlAlchemy : Serializing many-to-many relationships