如何确保子类具有与基督平均相同的初始分散器?

发布于 2025-01-24 19:21:33 字数 755 浏览 2 评论 0 原文

基本上,我试图定义一个符合 str 的所有可能初始化参数。

这就是我的代码的样子:

import uuid

class UniversalID(str):
    def __init__(self, val:str):
        super().__init__()
        try:
            uuid.UUID(hex=val)
            self=val
        except ValueError as inv_str:
            logging.error(msg=f'Invalid id queried {val}')
            raise inv_str

sample= uuid.uuid1().hex
isinstance(UniversalID(sample), str) # Shows true, as expected

但是不确定这是否是正确的方法,因为可能还有其他我不照顾的 str initialiser的参数。

这个问题可以推广到,如果我想在子类中使用一些验证检查的 __ INT __ 方法相同的论点和处理方式相同?更糟糕的是,我是否必须复制粘贴代码?

Basically, I am trying to define a subclass of string which conforms with the RFC UUID scheme. An object of this class can only exist if it conforms to the 8-4-4-4-12 hex string, else does not. So I need to check it during initialisation, but not sure how to account for all possible initialisation arguments of str.

This is how my code looks like:

import uuid

class UniversalID(str):
    def __init__(self, val:str):
        super().__init__()
        try:
            uuid.UUID(hex=val)
            self=val
        except ValueError as inv_str:
            logging.error(msg=f'Invalid id queried {val}')
            raise inv_str

sample= uuid.uuid1().hex
isinstance(UniversalID(sample), str) # Shows true, as expected

But not sure if this is the right approach, as there may be other arguments of str initialiser that I am not taking care of.

The question can be generalised to, if I want to modify the __init__ method with some validation check in the subclass, do I need to have total access to the initialiser in the base class, to make sure it accepts the same arguments and processes the same way? Worse still, do I have to, like, copy paste the code?

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

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

发布评论

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

评论(2

梨涡 2025-01-31 19:21:34

您可能需要创建一个从 uuid.uuid 继承的实例,并在将其传递给您的构造函数中,然后将其传递给您的构造函数。

You might want to create an instance that inherits from uuid.UUID and make the checks you want to the argument passed into your own constructor before you pass it to the super.

沫离伤花 2025-01-31 19:21:33

正如我在评论中所说的那样,您必须在其 __新__()方法中设置不变类型(如字符串)的价值。我找不到适合您的规范来源或示例 - 我从很久以前读过的一些书中知道这一点,所以决定为您组成一个(基于您的代码):

import logging
import uuid


class UniversalID(str):
    # You don't really need to define this, because it's what would happen anyway.
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        try:
            uuid.UUID(hex=self)
        except ValueError as inv_str:
            logging.error(msg=f'Invalid id queried {self}')
            raise inv_str


if __name__ == '__main__':

    sample1 = uuid.uuid1().hex
    try:
        isinstance(UniversalID(sample1), str)
    except ValueError as exc:
        print(f'ERROR: {exc} {sample1=!r}')
    else:
        print(f'{sample1=!r} is a valid hex uuid.')

    print()
    sample2 = 'not a hex uuid'
    try:
        isinstance(UniversalID(sample2), str)
    except ValueError as exc:
        print(f'ERROR: {exc} {sample2=!r}')
    else:
        print(f'{sample2=!r} is a valid hex uuid.')

As I said in a comment you have to set the value of immutable types, like strings, in their __new__() method. I couldn't find a canonical source or example for you — I know about it from some books I read long ago, so decided just to make up one for you (based on your code):

import logging
import uuid


class UniversalID(str):
    # You don't really need to define this, because it's what would happen anyway.
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        try:
            uuid.UUID(hex=self)
        except ValueError as inv_str:
            logging.error(msg=f'Invalid id queried {self}')
            raise inv_str


if __name__ == '__main__':

    sample1 = uuid.uuid1().hex
    try:
        isinstance(UniversalID(sample1), str)
    except ValueError as exc:
        print(f'ERROR: {exc} {sample1=!r}')
    else:
        print(f'{sample1=!r} is a valid hex uuid.')

    print()
    sample2 = 'not a hex uuid'
    try:
        isinstance(UniversalID(sample2), str)
    except ValueError as exc:
        print(f'ERROR: {exc} {sample2=!r}')
    else:
        print(f'{sample2=!r} is a valid hex uuid.')

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文