枚举中的腌制物体?

发布于 2025-02-07 22:07:15 字数 1610 浏览 2 评论 0原文

我正在从事一个工作项目,并且在腌制方面有问题。

这是我要做的事情的简化:

import pickle
from enum import Enum


class SiteInformation:
    def __init__(self, name, location):
        self.name = name
        self.location = location

        # Would actually be doing a number of calcs with name and location and storing
        # as members.
        self.time_zone = 'UTC'


class Site(Enum):
    GN = SiteInformation('North Site', 'Location String1')
    GS = SiteInformation('South Site', 'Location String2')


if __name__ == '__main__':
    print('Pickling...')
    with open('site_test', 'wb') as f:
        pickle.dump(Site.GN, f)
        pickle.dump(Site.GS, f)

    print('Unpickling...')
    with open('site_test', 'rb') as f:
        data = pickle.load(f)
    print(data)

当我运行此操作时,它在未挑剔的过程中失败:

Traceback (most recent call last):
  File "/Users/seb/Development/Scheduler/scripts/pickle_test.py", line 27, in <module>
    data = pickle.load(f)
  File "/Applications/Anaconda/anaconda3/envs/Scheduler/lib/python3.10/enum.py", line 385, in __call__
    return cls.__new__(cls, value)
  File "/Applications/Anaconda/anaconda3/envs/Scheduler/lib/python3.10/enum.py", line 710, in __new__
    raise ve_exc
ValueError: <__main__.SiteInformation object at 0x7fd77007ed40> is not a valid Site

我认为这与__ INT __ INT __ INT __SiteInformation中调用 ,但是我不太确定如何解决此问题,因为我在腌制方面几乎没有经验。我尝试在siteInformation中实现__ epr __方法,但这无非是使valueerror更可读。

任何帮助将不胜感激。

I'm working on a project for work and am having an issue with pickling.

Here is a simplification of what I am trying to do:

import pickle
from enum import Enum


class SiteInformation:
    def __init__(self, name, location):
        self.name = name
        self.location = location

        # Would actually be doing a number of calcs with name and location and storing
        # as members.
        self.time_zone = 'UTC'


class Site(Enum):
    GN = SiteInformation('North Site', 'Location String1')
    GS = SiteInformation('South Site', 'Location String2')


if __name__ == '__main__':
    print('Pickling...')
    with open('site_test', 'wb') as f:
        pickle.dump(Site.GN, f)
        pickle.dump(Site.GS, f)

    print('Unpickling...')
    with open('site_test', 'rb') as f:
        data = pickle.load(f)
    print(data)

When I run this, it fails during the unpickling:

Traceback (most recent call last):
  File "/Users/seb/Development/Scheduler/scripts/pickle_test.py", line 27, in <module>
    data = pickle.load(f)
  File "/Applications/Anaconda/anaconda3/envs/Scheduler/lib/python3.10/enum.py", line 385, in __call__
    return cls.__new__(cls, value)
  File "/Applications/Anaconda/anaconda3/envs/Scheduler/lib/python3.10/enum.py", line 710, in __new__
    raise ve_exc
ValueError: <__main__.SiteInformation object at 0x7fd77007ed40> is not a valid Site

I assume that this has to do with the __init__ call in SiteInformation, but I'm not quite sure how to fix this as I have little experience with pickling. I have tried implementing a __repr__ method in SiteInformation but this did nothing more than make the ValueError more readable.

Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巨坚强 2025-02-14 22:07:15

在Python 3.11中,这将按照书面形式工作。在较早的Pythons中,您需要添加__ eq __(加上__ Hash __,如果您想要set> set> set> set()dict(dict)支持 1 )启用siteInformation的不同实例,其值相同的值相等:

class SiteInformation:
    def __init__(self, name, location):
        self.name = name
        self.location = location

        # Would actually be doing a number of calcs with name and location and storing
        # as members.
        self.time_zone = 'UTC'

    def __eq__(self, other):
        return self.name == other.name and self.location == other.location

注意:__ eq __ eq __仅显示的目的。一个“真实” __ eq __看起来像:

def __eq__(self, other):
    if not isinstance(other, self.__class__):
        return NotImplemented
    return self.name == other.name and self.location == other.location

__ hash __看起来像:

def __hash__(self):
    return hash(self.name + self.location)

1:__ hash ____ ____,将对象放在set(),或用作dict()中的键。

In Python 3.11 this will work as written. In earlier Pythons you will need to add an __eq__ (plus __hash__ if you want set() and dict() support1) to enable different instances of SiteInformation with the same values to compare equal:

class SiteInformation:
    def __init__(self, name, location):
        self.name = name
        self.location = location

        # Would actually be doing a number of calcs with name and location and storing
        # as members.
        self.time_zone = 'UTC'

    def __eq__(self, other):
        return self.name == other.name and self.location == other.location

Note: the __eq__ shown is for example purposes only. A "real" __eq__ would look like:

def __eq__(self, other):
    if not isinstance(other, self.__class__):
        return NotImplemented
    return self.name == other.name and self.location == other.location

A __hash__ could look like:

def __hash__(self):
    return hash(self.name + self.location)

1: __hash__ is needed for an object to be in a set(), or to be used as a key in a dict().

筑梦 2025-02-14 22:07:15

看来这已经解决了问题,并使代码基库更加清洁(基于Planet enum python文档中的示例):

class Site(Enum):
    GN = ('North Site', 'Location String1')
    GS = ('South Site', 'Location String2')
    
    def __init__(self, site_name: str, location: str):
        self.site_name = site_name
        self.location = location
        self.time_zone = 'UTC'
        # Insert other member calculations here

It seems that this has fixed the problem and made the code base considerably cleaner (based off the Planet example in the Enum Python docs):

class Site(Enum):
    GN = ('North Site', 'Location String1')
    GS = ('South Site', 'Location String2')
    
    def __init__(self, site_name: str, location: str):
        self.site_name = site_name
        self.location = location
        self.time_zone = 'UTC'
        # Insert other member calculations here
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文