Python 使用 __slots__ 字典进行初始化是否有效?

2024-03-12

在寻找一种方便的方法来初始化插槽时,我有stupid?的想法wrongly? using __slots__字典如下图所示。

注:有一个相关的question https://stackoverflow.com/questions/41893267/how-to-use-slots-with-initialization-of-attributes/69491913在我之前发布过我的想法的地方answer https://stackoverflow.com/a/69491913/13613140,但我认为从中创建一个新问题可能更有用,因为我真的很想获得更多反馈。

所以我很感激以下“技巧”的任何注释/建议/问题:

class Slotted:

    __slots__ = {}

    def __new__(cls, *args, **kwargs):
        inst = super().__new__(cls)
        for key, value in inst.__slots__.items():
            setattr(inst, key, value)
        return inst

class Magic(Slotted):

    __slots__ = {
        "foo": True,
        "bar": 17
    }
magic = Magic()

print(f"magic.foo = {magic.foo}")
print(f"magic.bar = {magic.bar}")
magic.foo = True
magic.bar = 17

这样做可以/安全吗? 有什么缺点或者可能出现的问题等吗?

Edit:

After 亚历克斯·韦古德 https://stackoverflow.com/users/13990016/alex-waygood提到了 Python 3.8+ 中的文档目的,我提出了一个扩展,其中还包括对进一步子类化的更正 - 现在它变得有点冗长:

class Slot(str):

    __slots__ = ["init"]

    def __new__(cls, init, doc=""):
        obj = str.__new__(cls, doc)
        obj.init = init
        return obj

    def __call__(self):
        return self.init

class Slotted:

    __slots__ = {}

    def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        for base in reversed(cls.__mro__[:-1]):
            if isinstance(base.__slots__, dict):
                for key, value in base.__slots__.items():
                    if isinstance(value, Slot):
                        setattr(obj, key, value())
                    else:
                        raise TypeError(
                            f'Value for slot "{key}" must'
                            f' be of type "{Slot.__name__}"'
                        )
        return obj
class Magic(Slotted):
    """This class is not so boring any more"""

    __slots__ = {
        "foo": Slot(2, doc="Some quite interesting integer"),
        "bar": Slot(3.1416, doc="Some very exciting float")
    }

help(Magic)
magic = Magic()
print(f"magic.__slots__ = {magic.__slots__}")
print(f"magic.foo = {magic.foo}")
print(f"magic.bar = {magic.bar}")
Help on class Magic in module __main__:

class Magic(Slotted)
 |  Magic(*args, **kwargs)
 |  
 |  This class is not so boring any more
 |  
 |  Method resolution order:
 |      Magic
 |      Slotted
 |      builtins.object
 |  
 |  Data descriptors defined here:
 |  
 |  bar
 |      Some very exciting float
 |  
 |  foo
 |      Some quite interesting integer
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from Slotted:
 |  
 |  __new__(cls, *args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.

magic.__slots__ = {'foo': 'Some quite interesting integer', 'bar': 'Some very exciting float'}
magic.foo = 2
magic.bar = 3.1416

据我所知know,定义能力的预期用途__slots__ as a dict用于文档目的。

(我不知道在哪里(如果有的话)记录了这一点,也不知道它何时被添加到 Python 中。我确实知道这种行为在 Python 3.8、3.9、3.10 以及截至 14/10 的 3.11 alpha 0 中是一致的/ 2021。我还没有在 Python

如果我有课Foo,像这样:

class Foo:
    """The Foo class is for doing Foo-y things (obviously)."""
    
    __slots__ = {
        'bar': 'Some information about the bar attribute',
        'baz': 'Some information about the baz attribute'
    }

然后打电话help(Foo)在交互式终端中会产生以下输出:

>>> help(Foo)
Help on class Foo in module __main__:

class Foo(builtins.object)
 |  The Foo class is for doing Foo-y things (obviously).
 |  
 |  Data descriptors defined here:
 |  
 |  bar
 |      Some information about the bar attribute
 |  
 |  baz
 |      Some information about the baz attribute

如果我打电话help()在你的Magic类,但是,我得到以下输出:

>>> help(Magic)
Help on class Magic in module __main__:

class Magic(Slotted)
 |  Magic(*args, **kwargs)
 |  
 |  Method resolution order:
 |      Magic
 |      Slotted
 |      builtins.object
 |  
 |  Data descriptors defined here:
 |  
 |  bar
 |  
 |  foo
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from Slotted:
 |  
 |  __new__(cls, *args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.

话虽如此——我认为没有任何地方可以表明你can't做你在问题中建议的事情。它似乎工作得很好,所以如果你不太关心你的类的文档,并且它使你的代码更加干燥,我说那就去做吧!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 使用 __slots__ 字典进行初始化是否有效? 的相关文章

  • 为什么 Mypy 在 __init__ 中分配已在类主体中进行类型提示的属性时不给出键入错误?

    这是我的示例 python 文件 class Person name str age int def init self name age self name name self age age p Person 5 5 但当我跑步时myp
  • Flask-SocketIO redis 订阅

    我在用着https github com miguelgrinberg Flask SocketIO https github com miguelgrinberg Flask SocketIO实现 WebSocket 服务器 我需要从另一
  • 从所有数据帧列中删除子字符串

    我有一个单词列表 大约 1000 个单词 我称之为负面单词 CAST ARTICLES SANITARY JAN CLAUSES SPECIAL ENDORSEMENT 我很快就会用这个单词列表制作一个数据框 我还有一个数据框 看起来像 F
  • 如何同时运行多个功能[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有以下代码 my func1 my func2 my func3 my func4 my func5 是否可以同时计算函数的数据 而
  • 使用 Python 和 lmfit 拟合复杂模型?

    我想适合椭偏仪 http en wikipedia org wiki Ellipsometry使用 LMFit 将数据转换为复杂模型 两个测量参数 psi and delta 是复杂函数中的变量rho 我可以尝试将问题分离为实部和虚部共享参
  • Python,Google Places API - 给定一组纬度/经度查找附近的地点

    我有一个由商店 ID 及其纬度 经度组成的数据框 我想迭代该数据框 并使用 google api 为每个商店 ID 查找附近的关键地点 例如输入 Store ID LAT LON 1 1 222 2 222 2 2 334 4 555 3
  • Scrapy 文件管道不下载文件

    我的任务是构建一个可以下载所有内容的网络爬虫 pdfs 在给定站点中 Spider 在本地计算机和抓取集线器上运行 由于某种原因 当我运行它时 它只下载一些但不是全部的 pdf 通过查看输出中的项目可以看出这一点JSON 我已经设定MEDI
  • 使用 Tkinter 打开网页

    因此 我的应用程序需要能够打开其中的单个网页 并且它必须来自互联网并且未保存 特别是我想使用 Tkinter GUI 工具包 因为它是我最熟悉的工具包 最重要的是 我希望能够在窗口中生成事件 例如单击鼠标 但无需实际使用鼠标 有什么好的方法
  • Python speedtest.net,或等效的[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 是否有一个 Python 库可以实现 SpeedTest net 测试或等效的互联网连接速度测试 GitHub上有一个项目叫速度检查 https gi
  • 了解 Python 2.7 中的缩进错误

    在编写 python 代码时 我往往会遇到很多缩进错误 有时 当我删除并重写该行时 错误就会消失 有人可以为菜鸟提供 python 中 IndentationErrors 的高级解释吗 以下是我在玩 CheckIO 时收到的最近 inden
  • multiprocessing.Queue 中的 ctx 参数

    我正在尝试使用 multiprocessing Queue 模块中的队列 实施 https docs python org 3 4 library multiprocessing html exchang objects Between p
  • 在 django 中导入设置时出现奇怪的错误

    我有很多项目在 ubuntu 中使用 python2 7 和 virtualenv virtualenvwrapper 工作 在我的工作中 一些开发人员使用 macosx 和 windows 通常我像往常一样创建项目 django admi
  • Snakemake:将多个输入用于具有多个子组的一个输出的规则

    我有一个工作管道 用于下载 比对和对公共测序数据执行变体调用 问题是它目前只能在每个样本的基础上工作 i e作为每个单独测序实验的样本 如果我想对一组实验 例如样本的生物和 或技术复制 执行变体调用 则它不起作用 我试图解决它 但我无法让它
  • 哪种方式最适合Python工厂注册?

    这是一个关于这些方法中哪一种被认为是最有效的问题 Pythonic 我不是在寻找个人意见 而是在寻找惯用的观点 我的背景不是Python 所以这会对我有帮助 我正在开发一个可扩展的 Python 3 项目 这个想法类似于工厂模式 只不过它是
  • 数据损坏 C++ 和 Python 之间的管道

    我正在编写一些代码 从 Python 获取二进制数据 将其通过管道传输到 C 对数据进行一些处理 在本例中计算互信息度量 然后将结果通过管道传输回 Python 在测试时 我发现如果我发送的数据是一组尺寸小于 1500 X 1500 的 2
  • 根据标点符号列表替换数据框中的标点符号[重复]

    这个问题在这里已经有答案了 使用 Canopy 和 Pandas 我有数据框 a 其定义如下 a pd read csv text txt df pd DataFrame a df columns test test txt 是一个单列文件
  • 将 Django 中的所有视图限制为经过身份验证的用户

    我是 Django 新手 我正在开发一个项目 该项目有一个登录页面作为其索引和一个注册页面 其余页面都必须仅限于登录用户 如果未经身份验证的用户尝试访问这些页面 则必须将他 她重定向到登录页面 我看到 login required装饰器会将
  • 如何在引发异常时将变量传递给异常并在异常时检索它?

    现在我只有一个空白的异常类 我想知道如何在引发变量时给它一个变量 然后在 try except 中处理它时检索该变量 class ExampleException Exception pass 为其构造函数提供一个参数 将其存储为属性 然后
  • SQLAlchemy 与 count、group_by 和 order_by 使用 ORM

    我有几个函数需要使用 count group by 和 order by 进行一对多连接 我使用 sqlalchemy select 函数生成一个查询 该查询将返回一组 id 然后我对其进行迭代以对各个记录执行 ORM 选择 我想知道是否有
  • py2exe ImportError:没有名为 的模块

    我已经实现了一个名为 myUtils 的包 它由文件夹 myUtils 文件 组成 init py 和许多名称为 myUtils 的 py 文件 该包包含在 myOtherProject py 中 当我从 Eclipse 运行它们时可以找到

随机推荐