Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Edit:</strong> I've modified the code with my answer a bit more from @unutbu's original to simplify it and make what is being done clearer. In the latest version, the <code>@staticmethod</code>'s have been eliminated altogether and replaced with nested one-liners. The outer function and nested class have been renamed <code>AutoFloatProperties</code> and <code>_AutoFloatProperties</code> to reflect their specialized behavior of converting and storing the values assigned as floats. Despite all this, @unutbu's own revised answer using a class decorator instead of a metaclass is a slightly simpler solution, although the internals and usage are very similar.</p> <pre><code>def AutoFloatProperties(*props): '''metaclass''' class _AutoFloatProperties(type): # Inspired by autoprop (http://www.python.org/download/releases/2.2.3/descrintro/#metaclass_examples) def __init__(cls, name, bases, cdict): super(_AutoFloatProperties, cls).__init__(name, bases, cdict) for attr in props: def fget(self, _attr='_'+attr): return getattr(self, _attr) def fset(self, value, _attr='_'+attr): setattr(self, _attr, float(value)) setattr(cls, attr, property(fget, fset)) return _AutoFloatProperties class Vector(object): '''Creates a Maya vector/triple, having x, y and z coordinates as float values''' __metaclass__ = AutoFloatProperties('x','y','z') def __init__(self, x=0, y=0, z=0): self.x, self.y, self.z = x, y, z # values converted to float via properties if __name__=='__main__': v=Vector(1,2,3) print(v.x) # 1.0 v.x=4 print(v.x) # 4.0 </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