Change representation of Python object -


in python, data types (like int, float) both represent value, have built-in attributes/functions/etc:

in [1]: = 1.2  in [2]: out[2]: 1.2  in [3]: a.is_integer() out[3]: false 

is possible reproduce behavior within python, e.g. define class:

class scalar:     def __init__(self, value)         self.value = value      # other code ....  s = scalar(1.2) 

where have s return 1.2 (instead of typing s.value), , things a = s -> a = 1.2? closest can behavior adding like:

def __getitem__(self, key=none):     return self.value 

and using a = s[()], doesn't good.

where have s return 1.2 (instead of typing s.value)

in console? implement __repr__ method.

a = s -> = 1.2

to avoid having use a = s.value, can implement __call__ , call object:

>>> class scalar: ...     def __init__(self, value): ...         self.value = value ...     def __repr__(self): ...         return str(self.value) ...     def __call__(self): ...         return self.value ...  >>> s = scalar(1.2) >>> s 1.2 >>> = s() >>> 1.2 

check documentation data model on emulating numeric types.

for example:

class scalar:     def __init__(self, value):         self.value = value     def __repr__(self):         return str(self.value)     def __call__(self):         return self.value     def __add__(self, other):         return scalar(self.value + other.value)     def __lt__(self, other):         return self.value < other.value     def ___le__(self, other):         return self.value <= other.value     def __eq__(self, other):         return self.value == other.value     def __ne__(self, other):         return self.value != other.value     def __gt__(self, other):         return self.value > other.value     def __ge__(self, other):         return self.value >= other.value 

can used this:

>>> s1 = scalar(1.2) >>> s2 = scalar(2.1) >>> s1 + s2 3.3 >>> s1 < s2 true >>> s1 > s2 false >>> s1 != s2 true >>> s1 <= s2 true >>> s1 >= s2 false 

there __int__ , __float__ magic methods, can implement , use (this more semantically correct):

>>> = int(s) >>> = float(s) 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -