Python 中的模板类

如何解决Python 中的模板类

我正在尝试用 Python 创建代数,但我发现很难创建参数化类。

以这个 ProductWeight 类为例。它包含另外两个 Weight 对象,具有强制类型(至少是静态的,通过 mypy)。

这将失败,因为(按照设计)我无法访问 W1W2 的类来调用它们的类方法,例如 zero。 (它们没有被指定;ProductWeight 没有被模板化。)当我创建一个实例时,ProductWeight 不知道要绑定到它的类型。

from typing import Generic,TypeVar
W1 = TypeVar("W1")
W2 = TypeVar("W2")

class ProductWeight(Generic[W1,W2]):
    def __init__(self,value1: W1,value2: W2):
        self.value1_ = value1
        self.value2_ = value2

    @classmethod
    def zero(cls):
        return cls(W1.zero(),W2.zero())  # Will fail - no access to W1 and W2.
    

相比之下,这在 C++ 中很简单:因为类型是参数化的,所以可以查找 W1::Zero

template<typename W1,typename W2>
public:
    ProductWeight(W1 w1,W2 w2) : value1_(w1),value2_(w2) {}
    static ProductWeight Zero() {
        return ProductWeight(W1::Zero(),W2::Zero());
    }
private:
    W1 value1_;
    W2 value2_;
};

在 Python 中是否有解决方法?创建一个内部类,或者以其他方式向类(而不是类实例)提供类型?

为了尽量减少可重现的示例,您可以使用另一种 Weight 类型的这种实现。

class SimpleWeight:
    def __init__(self,value):
        assert value in {True,False}
        self.value_ = value

    @classmethod
    def zero(cls):
        return cls(False)

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight(weight1,weight2)

print(SimpleWeight.zero())  # So far,so good.
print(ProductWeight.zero())  # Oof.
# Predictably,it failed because `ProductWeight` is not specialized.

这是可预测的错误消息:

Traceback (most recent call last):
  File "garbage.py",line 32,in <module>
    print(ProductWeight.zero())  # Oof.
  File "garbage.py",line 14,in zero
    return cls(W1.zero(),W2.zero())  # Will fail - no access to W1 and W2.
AttributeError: 'TypeVar' object has no attribute 'zero'

理想情况下,可以像这样创建参数类型:

product = ProductWeight[SimpleWeight,SimpleWeight](weight1,weight2)
# And similarly:
print(ProductWeight[SimpleWeight,SimpleWeight].zero())

解决方法

要解决这个问题,最重要的是要意识到 C++ 中的泛型会创建多个类,而在 Python 中,无论其构造函数中的参数是什么类型,您将始终只有一个类。

换句话说,在C++中vector<int>vector<string>是两个类。如果将它们绑定到 Python 解释器,则必须为它们分配两个不同的名称,例如 VectorIntVectorString

代码

def ProductWeight(value1,value2):
    def init(self,value1,value2):
        self.value1 = value1
        self.value2 = value2

    def zero(cls):
        return cls(cls.W1.zero(),cls.W2.zero())

    W1 = type(value1)
    W2 = type(value2)
    name = f'ProductWeight{W1}{W2}'

    try:
        return ProductWeight.types[name](value1,value2)
    except KeyError:
        pass

    cls = type(name,(),{'__init__': init})
    cls.W1 = W1
    cls.W2 = W2
    cls.zero = classmethod(zero)
    ProductWeight.types[name] = cls

    return cls(value1,value2)

ProductWeight.types = {}

class SimpleWeight:
    def __init__(self,value):
        assert value in {True,False}
        self.value_ = value

    @classmethod
    def zero(cls):
        return cls(False)

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight(weight1,weight2)

print(SimpleWeight.zero())
print(type(product).zero())

代码尝试尊重您的原始 API,您可以使用通用参数创建类 ProductWeight 的实例。但是,如果要调用实例的类方法 zero,则必须访问实例的底层类型(注意最后一行从 ProductWeight 更改为 type(product))。

为方便起见,您可以将此引用保存到一个变量。

函数 ProductWeight 用作通用工厂。每次调用它时,它都会根据参数的类型为新类创建一个名称。如果这样的类已经存在,它只返回它的一个新实例。否则,它使用 type 函数创建新类,然后返回一个新实例。

ProductWeight 本身也是一个具有已创建类型字典的单例对象。

结论

您可能会注意到,该解决方案使用的内存明显多于其 C++ 对应方案。但是,考虑到您选择使用 Python 而不是 C++,您可能不会太担心。

更重要的是,您必须决定这是否适合您。请记住,在 Python 中没有泛型,只有“动态”。所以从长远来看,你的思维方式带来的障碍比它消除的障碍要多。

让 Python 听起来像 C++

这部分回答您的问题的此编辑:

理想情况下,可以像这样创建参数类型:

product = ProductWeight[SimpleWeight,SimpleWeight](weight1,weight2)
# And similarly:
print(ProductWeight[SimpleWeight,SimpleWeight].zero())

不要害怕,因为这实际上是可能的。以下代码使用 Python 3.7 中的 __class_getitem__,但有一个变通方法,它也可以在旧版本上运行,请参阅此 question about static getitem method

代码重写

# SimpleWeight didn't change
from simple_weight import SimpleWeight

class ProductWeight:
    types = {}

    def __class_getitem__(cls,key):
        try:
            W1,W2 = key
        except ValueError:
            raise Exception('ProductWeight[] takes exactly two arguments.')

        name = f'{ProductWeight.__name__}<{W1.__name__},{W2.__name__}>'

        try:
            return cls.types[name]
        except KeyError:
            pass

        new_type = type(name,{'__init__': cls.init})
        new_type.W1 = W1
        new_type.W2 = W2
        new_type.zero = classmethod(cls.zero)
        cls.types[name] = new_type

        return new_type

    def __init__(self):
        raise Exception('ProductWeight is a static class and cannot be instantiated.')

    def init(self,cls.W2.zero())

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight[SimpleWeight,weight2)

print(SimpleWeight.zero())
print(ProductWeight[SimpleWeight,SimpleWeight].zero())

这利用了这样一个事实,即括号运算符 __getitem__ 接受任意数量的参数并将它们打包成一个元组,这是它的第一个参数。您可以解压缩元组并获取所有类型。这可以扩展到任何数量的类型,甚至是在运行时选择的数量。

推断类型

上一个版本失去了从传递给构造函数的参数推断类型的能力。通过创建抽象工厂,我们可以恢复此功能。

# SimpleWeight didn't change
from simple_weight import SimpleWeight

class ProductWeightAbstractFactory:
    def __call__(self,value2):
        return self[type(value1),type(value2)](value1,value2)

    def __getitem__(self,types):
        W1,W2 = types
        name = f'ProductWeight<{W1.__name__},{W2.__name__}>'

        try:
            return self.types[name]
        except KeyError:
            pass

        cls = type(self)
        new_type = type(name,{'__init__': cls.init})
        new_type.W1 = W1
        new_type.W2 = W2
        new_type.zero = classmethod(cls.zero)
        self.types[name] = new_type

        return new_type

    def __init__(self):
        self.types = {}

    def init(self,cls.W2.zero())

ProductWeight = ProductWeightAbstractFactory()

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight[SimpleWeight,weight2)
inferred_product = ProductWeight(weight1,SimpleWeight].zero())
print(type(inferred_product).zero())

注意,在使用之前你必须创建一个工厂的实例:

ProductWeight = ProductWeightAbstractFactory()

现在您可以使用方括号创建具有显式类型的对象:

product = ProductWeight[SimpleWeight,weight2)

或者你可以推断类型以使代码简洁:

product = ProductWeight(weight1,weight2)

现在它比以往任何时候都更接近于类似 C++ 的语法。

类型检查

为了在开发时提供更多安全性,您还可以在构造函数中引入类型检查。

def init(self,value2):
    def check_types(objects,required_types):
        for index,(obj,t) in enumerate(zip(objects,required_types)):
            if not issubclass(type(obj),t):
                raise Exception(f'Parameter {index + 1} is not a subclass of its required type {t}.')

    cls = type(self)
    check_types((value1,value2),(cls.W1,cls.W2))

    self.value1 = value1
    self.value2 = value2

此代码将失败:

product = ProductWeight[SimpleWeight,SimpleWeight](1,2)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res