如何解决Python 中的模板类
我正在尝试用 Python 创建代数,但我发现很难创建参数化类。
以这个 ProductWeight
类为例。它包含另外两个 Weight
对象,具有强制类型(至少是静态的,通过 mypy
)。
这将失败,因为(按照设计)我无法访问 W1
和 W2
的类来调用它们的类方法,例如 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 解释器,则必须为它们分配两个不同的名称,例如 VectorInt
和 VectorString
。
代码
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 举报,一经查实,本站将立刻删除。