Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This works, and is less gross after several improvements (props to @jchl), but still seems like it should be unecessary, especially considering that you get this for free with "old-style" classes. </p> <p>I'm still looking for a better answer. If there's no better method, this seems to me like a regression in the Python language.</p> <pre><code>def ops_list(): "calculate the list of overloadable operators" #&lt;type 'object'&gt; has functions but no operations not_ops = dir(object) #calculate the list of operation names ops = set() for mytype in (int, float, str): for op in dir(mytype): if op.endswith("__") and op not in not_ops: ops.add(op) return sorted(ops) class MetaCastable(type): __ops = ops_list() def __new__(mcs, name, bases, dict): #pass any undefined ops to self.__op__ def add_op(op): if op in dict: return fn = lambda self, *args: self.__op__(op, args) fn.__name__ = op dict[op] = fn for op in mcs.__ops: add_op( op ) return type.__new__(mcs, name, bases, dict) class Castable(object): __metaclass__ = MetaCastable def __str__(self): print "str!" return "&lt;Castable&gt;" def __int__(self): print "int!" return 42 def __float__(self): print "float!" return 2.718281828459045 def __op__(self, op, args): try: other = args[0] except IndexError: other = None print "%s %s %s" % (self, op, other) self, other = coerce(self, other) return getattr(self, op)(*args) def __coerce__(self, other): print "coercing like %r!" % other if other is None: other = 0.0 return (type(other)(self), other) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload