python3:singledispatch na classe, como despachar o tipo próprio
-
02-01-2020 - |
Pergunta
Usando python3.4.Aqui eu quero usar singledispatch para despachar tipos diferentes __mul__
método.O código assim:
class Vector(object):
## some code not paste
@functools.singledispatch
def __mul__(self, other):
raise NotImplementedError("can't mul these type")
@__mul__.register(int)
@__mul__.register(object) # Becasue can't use Vector , I have to use object
def _(self, other):
result = Vector(len(self)) # start with vector of zeros
for j in range(len(self)):
result[j] = self[j]*other
return result
@__mul__.register(Vector) # how can I use the self't type
@__mul__.register(object) #
def _(self, other):
pass # need impl
Como você pode ver o código, quero suporte Vector*Vertor
, Isso tem erro de nome
Traceback (most recent call last):
File "p_algorithms\vector.py", line 6, in <module>
class Vector(object):
File "p_algorithms\vector.py", line 84, in Vector
@__mul__.register(Vector) # how can I use the self't type
NameError: name 'Vector' is not defined
A questão pode ser: Como posso usar o nome da classe como Type no método da classe?Eu sei que c++ tem instrução de classe de fonte.Como python resolve meu problema?E é estranho ver result = Vector(len(self))
onde o Vector
pode ser usado no método body .
Depois de dar uma olhada http://lukasz.langa.pl/8/single-dispatch-generic-functions/Posso escolher esta forma de implementar:
import unittest
from functools import singledispatch
class Vector(object):
"""Represent a vector in a multidimensional space."""
def __init__(self, d):
self._coords = [0 for i in range(0, d)]
self.__init__mul__()
def __init__mul__(self):
__mul__registry = self.__mul__.registry
self.__mul__ = singledispatch(__mul__registry[object])
self.__mul__.register(int, self.mul_int)
self.__mul__.register(Vector, self.mul_Vector)
def __setitem__(self, key, value):
self._coords[key] = value
def __getitem__(self, item):
return self._coords[item]
def __len__(self):
return len(self._coords)
def __str__(self):
return str(self._coords)
@singledispatch
def __mul__(self, other):
print ("error type is ", type(other))
print (type(other))
raise NotImplementedError("can't mul these type")
def mul_int(self,other):
print ("other type is ", type(other))
result = Vector(len(self)) # start with vector of zeros
for j in range(len(self)):
result[j] = self[j]*other
return result
def mul_Vector(self, other):
print ("other type is ", type(other))
#result = Vector(len(self)) # start with vector of zeros
sum = 0
for i in range(0,len(self)):
sum += self._coords[i] * other._coords[i]
return sum
class TestCase(unittest.TestCase):
def test_singledispatch(self):
# the following demonstrates usage of a few methods
v = Vector(5) # construct five-dimensional <0, 0, 0, 0, 0>
for i in range(1,6):
v[i-1] = i
print(v.__mul__(3))
print(v.__mul__(v))
print(v*3)
if __name__ == "__main__":
unittest.main()
A resposta é estranha:
other type is <class 'int'> [3, 6, 9, 12, 15] other type is <class '__main__.Vector'> 55 error type is <class 'int'> Traceback (most recent call last): File "p_algorithms\vector.py", line 164, in <module> print(v*3) File "C:\Python34\lib\functools.py", line 710, in wrapper return dispatch(args[0].__class__)(*args, **kw) File "p_algorithms\vector.py", line 111, in __mul__ raise NotImplementedError("can't mul these type")
v.__mul__(3)
pode funcionar, mas v*3
não posso trabalhar.Isso é estranho Da minha opção v*3
é exatamente o mesmo que v.__mul__(3)
.
Atualização após o comentário de @Martijn Pieters, ainda quero implementar v*3
em aula.Então eu tento isso
import unittest
from functools import singledispatch
class Vector(object):
@staticmethod
def static_mul_int(self,other):
print ("other type is ", type(other))
result = Vector(len(self)) # start with vector of zeros
for j in range(len(self)):
result[j] = self[j]*other
return result
@singledispatch
@staticmethod
def __static_mul__(cls, other):
print ("error type is ", type(other))
print (type(other))
raise NotImplementedError("can't mul these type")
__mul__registry2 = __static_mul__.registry
__mul__ = singledispatch(__mul__registry2[object])
__mul__.register(int, static_mul_int)
def __init__(self, d):
self._coords = [0 for i in range(0, d)]
self.__init__mul__()
def __init__mul__(self):
__mul__registry = self.__mul__.registry
print ("__mul__registry",__mul__registry,__mul__registry[object])
self.__mul__ = singledispatch(__mul__registry[object])
self.__mul__.register(int, self.mul_int)
print ("at last __mul__registry",self.__mul__.registry)
# @singledispatch
# def __mul__(self, other):
# print ("error type is ", type(other))
# print (type(other))
# raise NotImplementedError("can't mul these type")
def mul_int(self,other):
print ("other type is ", type(other))
result = Vector(len(self)) # start with vector of zeros
for j in range(len(self)):
result[j] = self[j]*other
return result
def __setitem__(self, key, value):
self._coords[key] = value
def __getitem__(self, item):
return self._coords[item]
def __len__(self):
return len(self._coords)
def __str__(self):
return str(self._coords)
class TestCase(unittest.TestCase):
def test_singledispatch(self):
# the following demonstrates usage of a few methods
v = Vector(5) # construct five-dimensional <0, 0, 0, 0, 0>
for i in range(1,6):
v[i-1] = i
print(v.__mul__(3))
print("type(v).__mul__'s registry:",type(v).__mul__.registry)
type(v).__mul__(v, 3)
print(v*3)
if __name__ == "__main__":
unittest.main()
Desta vez . v.__mul__(3)
tem erro:
Traceback (most recent call last): File "test.py", line 73, in test_singledispatch type(v).__mul__(v, 3) File "/usr/lib/python3.4/functools.py", line 708, in wrapper return dispatch(args[0].__class__)(*args, **kw) TypeError: 'staticmethod' object is not callable
Para mim, o método estático deve funcionar como o método de instância.
Solução
Você não pode usar functools.singledispatch
em métodos de forma alguma, pelo menos não como decorador.Python 3.8 adiciona uma nova opção, apenas para métodos: functools.singledispatchmethod()
.
Não importa isso Vector
ainda não está definido aqui;o primeiro argumento para qualquer método sempre será self
, enquanto você usaria o envio único para o segundo argumento aqui.
Porque os decoradores se aplicam ao objetos de função antes que o objeto de classe seja criado, você também pode registrar seus 'métodos' como funções, fora do corpo da classe, para que você tenha acesso ao Vector
nome:
class Vector(object):
@functools.singledispatch
def __mul__(self, other):
return NotImplemented
@Vector.__mul__.register(int)
@Vector.__mul__.register(Vector)
def _(self, other):
result = Vector(len(self)) # start with vector of zeros
for j in range(len(self)):
result[j] = self[j]*other
return result
Para tipos não suportados, você precisa retornar o NotImplemented
único, não levante uma exceção.Dessa forma, o Python também tentará a operação inversa.
Porém, como o despacho vai chavear no argumento errado (self
) aqui de qualquer maneira, você terá que criar seu próprio mecanismo de despacho único.
Se você realmente quiser usar @functools.singledispatch
você teria que delegar para uma função regular, com os argumentos invertido:
@functools.singledispatch
def _vector_mul(other, self):
return NotImplemented
class Vector(object):
def __mul__(self, other):
return _vector_mul(other, self)
@_vector_mul.register(int)
def _vector_int_mul(other, self):
result = Vector(len(self))
for j in range(len(self)):
result[j] = self[j] * other
return result
Quanto às suas atualizações usando __init__mul__
: v * 3
é não traduzido para v.__mul__(3)
.Em vez disso, é traduzido para type(v).__mul__(v, 3)
, ver Pesquisa de método especial na referência do modelo de dados Python.Esse sempre ignora quaisquer métodos definidos diretamente na instância.
Aqui type(v)
é Vector
;Python procura o função, ele não usará um método vinculado aqui.Novamente, porque functools.singledispatch
despachos no primeiro argumento, sempre, você não pode usar despacho único diretamente nos métodos de Vector
, porque esse primeiro argumento sempre será um Vector
instância.
Em outras palavras, Python irá não use os métodos que você definiu self
em __init__mul__
;métodos especiais são nunca olhou para a instância, veja Pesquisa de método especial na documentação do modelo de dados.
O functools.singledispatchmethod()
opção que o Python 3.8 adiciona usa um aula como o decorador que implementa o protocolo descritor, assim como os métodos fazem.Isso permite que ele lide com o envio antes vinculativo (então antes self
seria anexado à lista de argumentos) e, em seguida, vincular a função registrada que o singledispatch
despachante retorna.O código fonte para esta implementação é totalmente compatível com versões mais antigas do Python, então você pode usá-lo:
from functools import singledispatch, update_wrapper
# Python 3.8 singledispatchmethod, backported
class singledispatchmethod:
"""Single-dispatch generic method descriptor.
Supports wrapping existing descriptors and handles non-descriptor
callables as instance methods.
"""
def __init__(self, func):
if not callable(func) and not hasattr(func, "__get__"):
raise TypeError(f"{func!r} is not callable or a descriptor")
self.dispatcher = singledispatch(func)
self.func = func
def register(self, cls, method=None):
"""generic_method.register(cls, func) -> func
Registers a new implementation for the given *cls* on a *generic_method*.
"""
return self.dispatcher.register(cls, func=method)
def __get__(self, obj, cls):
def _method(*args, **kwargs):
method = self.dispatcher.dispatch(args[0].__class__)
return method.__get__(obj, cls)(*args, **kwargs)
_method.__isabstractmethod__ = self.__isabstractmethod__
_method.register = self.register
update_wrapper(_method, self.func)
return _method
@property
def __isabstractmethod__(self):
return getattr(self.func, '__isabstractmethod__', False)
e aplique isso ao seu Vector()
aula.Você ainda precisa registrar seu Vector
implementação para o despacho único depois a turma foi criada, pois só assim você poderá cadastrar um despacho para a turma:
class Vector(object):
def __init__(self, d):
self._coords = [0] * d
def __setitem__(self, key, value):
self._coords[key] = value
def __getitem__(self, item):
return self._coords[item]
def __len__(self):
return len(self._coords)
def __repr__(self):
return f"Vector({self._coords!r})"
def __str__(self):
return str(self._coords)
@singledispatchmethod
def __mul__(self, other):
return NotImplemented
@__mul__.register
def _int_mul(self, other: int):
result = Vector(len(self))
for j in range(len(self)):
result[j] = self[j] * other
return result
@Vector.__mul__.register
def _vector_mul(self, other: Vector):
return sum(sc * oc for sc, oc in zip(self._coords, other._coords))
É claro que você também poderia criar uma subclasse primeiro e despachar com base nela, já que o despacho também funciona para subclasses:
class _Vector(object):
def __init__(self, d):
self._coords = [0] * d
class Vector(_Vector):
def __setitem__(self, key, value):
self._coords[key] = value
def __getitem__(self, item):
return self._coords[item]
def __len__(self):
return len(self._coords)
def __repr__(self):
return f"{type(self).__name__}({self._coords!r})"
def __str__(self):
return str(self._coords)
@singledispatchmethod
def __mul__(self, other):
return NotImplemented
@__mul__.register
def _int_mul(self, other: int):
result = Vector(len(self))
for j in range(len(self)):
result[j] = self[j] * other
return result
@__mul__.register
def _vector_mul(self, other: _Vector):
return sum(sc * oc for sc, oc in zip(self._coords, other._coords))
Outras dicas
Isto é um pouco feio, pois você precisa adiar a vinculação da implementação de Vector
/Vector
multiplicação até depois Vector
está realmente definido.Mas a ideia é que a função de despacho único precisa que o primeiro argumento seja de tipo arbitrário, então Vector.__mul__
chamará essa função com self
como segundo argumento.
import functools
class Vector:
def __mul__(self, other):
# Python has already dispatched Vector() * object() here, so
# swap the arguments so that our single-dispatch works. Note
# that in general if a*b != b*a, then the _mul_by_other
# implementations need to compensate.
return Vector._mul_by_other(other, self)
@functools.singledispatch
def _mul_by_other(x, y):
raise NotImplementedError("Can't multiply vector by {}".format(type(x)))
@_mul_by_other.register(int)
def _(x, y):
print("Multiply vector by int")
@Vector._mul_by_other.register(Vector)
def _(x, y):
print("Multiply vector by another vector")
x = Vector()
y = Vector()
x * 3
x * y
try:
x * "foo"
except NotImplementedError:
print("Caught attempt to multiply by string")