Python 删除数据类依赖项

Python 删除数据类依赖项,python,python-3.x,cookies,python-dataclasses,Python,Python 3.x,Cookies,Python Dataclasses,我使用的是Python 3.5,它不支持dataclass 有没有一种方法可以将下面的类转换为不使用dataclasses的类 from dataclasses import dataclass @dataclass class Cookie: """Models a cookie.""" domain: str flag: bool path: str secure: bool expiry: int name: str va

我使用的是Python 3.5,它不支持
dataclass

有没有一种方法可以将下面的类转换为不使用
dataclasses
的类

from dataclasses import dataclass

@dataclass
class Cookie:
    """Models a cookie."""

    domain: str
    flag: bool
    path: str
    secure: bool
    expiry: int
    name: str
    value: str

    def to_dict(self):
        """Returns the cookie as a dictionary.

        Returns:
            cookie (dict): The dictionary with the required values of the cookie

        """
        return {key: getattr(self, key) for key in ('domain', 'name', 'value', 'path')}

这是来自存储库的

您可以将代码转换为使用(这启发了
数据类
),或者手工写出类。考虑到您链接到的项目使用该类,而不是用于其他任何用途,手工编写该类非常简单:

class Cookie:
    """Models a cookie."""
    def __init__(self, domain, flag, path, secure, expiry, name, value):
        self.domain = domain
        self.flag = flag
        self.path = path
        self.secure = secure
        self.expiry = expiry
        self.name = name
        self.value = value

    def to_dict(self):
        """Returns the cookie as a dictionary.
        Returns:
            cookie (dict): The dictionary with the required values of the cookie
        """
        return {key: getattr(self, key) for key in ('domain', 'name', 'value', 'path')}
否则,
attrs
版本,避免使用变量注释(3.5中不支持):


但是,请注意,
locationsharinglib
仅支持Python 3.7,因此您可能会在该项目中遇到其他问题。

请注意,
locationsharinglib
表示它们仅支持3.7及更高版本。您可能还有其他问题。运行
pip install dataclasses
并且安装得很好,但是运行
from dataclasses import dataclass
会返回
f'name={self.name!r},
的语法错误,您的
self.X=X
解决方案工作得很好。只是需要删除
数据类的实例
@Bijan:啊,对不起,我错过了这个项目只在3.6上运行。。
@attr.s
class Cookie:
    """Models a cookie."""

    domain = attr.ib()
    flag = attr.ib()
    path = attr.ib()
    secure = attr.ib()
    expiry = attr.ib()
    name = attr.ib()
    value = attr.ib()

    def to_dict(self):
        """Returns the cookie as a dictionary.
        Returns:
            cookie (dict): The dictionary with the required values of the cookie
        """
        return {key: getattr(self, key) for key in ('domain', 'name', 'value', 'path')}