New attribute __convert__ for classes

This attribute will use for convertion classes to other types, i.e. int(MyClass) will return __convert__ result in MyClass Example: class MyClass: def __init__(self, numer: int): self.number = number def __convert__(self, type): assert type == int # Only integer is allowed return self.number*5 # Example test = MyClass(1) test_2 = MyClass(5) print( int(test) ) # 5 print( int(test2) ) # 25

On Sun, Jun 14, 2020 at 03:33:16PM -0000, artem6191 <artem129871@gmail.com> wrote:
Define ``__int__`` or ``__index__``. See https://docs.python.org/3/reference/datamodel.html#special-method-names Oleg. -- Oleg Broytman https://phdru.name/ phd@phdru.name Programmers don't die, they just GOSUB without RETURN.

On Sun, Jun 14, 2020 at 9:04 AM Oleg Broytman <phd@phdru.name> wrote:
or __float__ But the problem is that we need a dunder for each type you want to support. I think the idea here is that you could specify, in your own custom class, which type(s) you can convert to, and it could be any type. That being said, to the OP: what are your use cases here? adding a dunder requires compelling use cases, and in this case, why having a dunder would be more helpful that simply writing a convert to this type method on your class. And when would that dunder be called? I'm having trouble figuring that out. -CHB
-- Christopher Barker, PhD Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython

On Sun, Jun 14, 2020 at 03:33:16PM -0000, artem6191 <artem129871@gmail.com> wrote:
Define ``__int__`` or ``__index__``. See https://docs.python.org/3/reference/datamodel.html#special-method-names Oleg. -- Oleg Broytman https://phdru.name/ phd@phdru.name Programmers don't die, they just GOSUB without RETURN.

On Sun, Jun 14, 2020 at 9:04 AM Oleg Broytman <phd@phdru.name> wrote:
or __float__ But the problem is that we need a dunder for each type you want to support. I think the idea here is that you could specify, in your own custom class, which type(s) you can convert to, and it could be any type. That being said, to the OP: what are your use cases here? adding a dunder requires compelling use cases, and in this case, why having a dunder would be more helpful that simply writing a convert to this type method on your class. And when would that dunder be called? I'm having trouble figuring that out. -CHB
-- Christopher Barker, PhD Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython
participants (5)
-
artem6191
-
Christopher Barker
-
Jason Madden
-
Oleg Broytman
-
Soni L.