我使用的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')}
这是从locationsharinglib存储库中获得的
答案 0 :(得分:1)
您可以将代码转换为使用attrs
(这启发了dataclasses
),也可以只手工编写类。假定您链接到的项目使用类purely as a temporary dataholder而不是其他任何东西,那么手工编写起来就很简单:
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中不支持):
@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')}
但是请注意,locationsharinglib
states in their package metadata它们仅支持Python 3.7,因此您可能会在该项目中遇到其他问题。