473,545 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Storing value with limits in object

I'm trying to limit a value stored by object (either int or float):

class Limited(object) :
def __init__(self, value, min, max):
self.min, self.max = min, max
self.n = value
def set_n(self,valu e):
if value < self.min: # boundary check
self.n = self.min
if value self.max:
self.n = self.max
else:
self.n = value
n = property(lambda self : self._value, set_n)

This works, except I would like the class to behave like built-in types, so
I can use it like this:

a = Limited(7, 0, 10)
b = math.sin(a)

So that object itself returns it's value (which is stored in a.n). Is this
possible?

Jun 27 '08 #1
13 1642
On Sun, Jun 22, 2008 at 11:44 AM, Josip <fa*******@noon e.bewrote:
I'm trying to limit a value stored by object (either int or float):

class Limited(object) :
def __init__(self, value, min, max):
self.min, self.max = min, max
self.n = value
def set_n(self,valu e):
if value < self.min: # boundary check
self.n = self.min
if value self.max:
self.n = self.max
else:
self.n = value
n = property(lambda self : self._value, set_n)

This works, except I would like the class to behave like built-in types, so
I can use it like this:

a = Limited(7, 0, 10)
b = math.sin(a)

So that object itself returns it's value (which is stored in a.n). Is this
possible?
Not with normal vars, because = is a rebinding operator in Python,
rather than assignment.

You can do (close to) the above with object properties.

David.
Jun 27 '08 #2
Not with normal vars, because = is a rebinding operator in Python,
rather than assignment.

You can do (close to) the above with object properties.

David.
Yes, but it's done with built-in types like int and float. I suspect I could
subclass from them and implement limits, but I would have to make
seperate class for each type. Can I override conversion methods like int()
and float() within my class?
Jun 27 '08 #3
On Sun, Jun 22, 2008 at 12:24 PM, Josip <fa*******@noon e.bewrote:
>Not with normal vars, because = is a rebinding operator in Python,
rather than assignment.

You can do (close to) the above with object properties.

David.

Yes, but it's done with built-in types like int and float. I suspect I could
subclass from them and implement limits, but I would have to make
seperate class for each type. Can I override conversion methods like int()
and float() within my class?
I think I may have misread your original post.

ints and floats are internal , immutable types, with some class
goodness on top (so you can treat them like objects to a degree,
subclass from them, etc). Python's interpreter has built-in logic
which 'knows' how to use ints and floats variables, without calling
their special "__" methods. Python would be a lot slower if it worked
this way.

To do exactly what you want, you'd need to add a new internal numeric
type to Python.

You can subclass from float, and redefine __float__ and __int__, but
those will only be called when your code actually calls the builtin
float() and int() builtins, eg:

import math

class Float(float):
def __float__(self) :
raise NotImplementedE rror

a = Float(1)
print math.sin(a)

# Outputs 0.841470984808

a = Float(1)
print math.sin(float( a))

# Throws a NotImplementedE rror exception

There is no way (afaik) for an object to tell Python to call one of
it's methods to get a reference, or 'value' to the object (if there
was, it would make things really complicated). In Python you generally
need to update the logic used during a lookup to get that effect (ie,
in a.b.c, you can customise the a.b lookup, or the a.b.c lookup, but
not the a lookup itself).

In theory you could hack Python's internal locals or globals
dictionary so that it did something unusual while looking up your
object. But in practice this doesn't work, because the returned
objects (when you call globals() or locals()) attributes are readonly.
Probably because those internal lookup dicts are implemented in
optimized C not Python, and the C implementation doesn't let you
redefine it's internals via the Python interface.

David.
Jun 27 '08 #4
In theory you could hack Python's internal locals or globals
dictionary so that it did something unusual while looking up your
object. But in practice this doesn't work, because the returned
objects (when you call globals() or locals()) attributes are readonly.
Probably because those internal lookup dicts are implemented in
optimized C not Python, and the C implementation doesn't let you
redefine it's internals via the Python interface.

David.
I'll settle for implementing the __call__() method to return the value as I
have
no intention to mess around with Python's internal mechanisms.

Thanks a lot for your deep insight.
Jun 27 '08 #5
On Jun 22, 5:44 am, "Josip" <fake.m...@noon e.bewrote:
I'm trying to limit a value stored by object (either int or float):

class Limited(object) :
def __init__(self, value, min, max):
self.min, self.max = min, max
self.n = value
def set_n(self,valu e):
if value < self.min: # boundary check
self.n = self.min
if value self.max:
self.n = self.max
else:
self.n = value
n = property(lambda self : self._value, set_n)

This works,
I bet you didn't even try this, unless your definition of "works"
includes a "RuntimeErr or: maximum recursion depth exceeded". Here's a
a working version:

class Limited(object) :
def __init__(self, value, min, max):
self.min, self.max = min, max
self.n = value

n = property(lambda self : self._value,
lambda self,value:
self.__dict__._ _setitem__('_va lue',
max(self.min, min(value,
self.max))))

def __int__(self): return int(self._value )
def __float__(self) : return float(self._val ue)
a = Limited(11, 0, 9)
print float(a)
import math
print math.sqrt(a)
except I would like the class to behave like built-in types, so
I can use it like this:

a = Limited(7, 0, 10)
b = math.sin(a)

So that object itself returns it's value (which is stored in a.n). Is this
possible?
For (most) math.* functions it suffices to define __float__, so the
above works. For making it behave (almost) like a regular number,
you'd have to write many more special methods: http://docs.python.org/ref/numeric-types.html.
Here's a possible start:

import operator

class Limited(object) :
def __init__(self, value, min, max):
self.min, self.max = min, max
self.n = value

n = property(lambda self : self._value,
lambda self,value:
self.__dict__._ _setitem__('_va lue',
max(self.min, min(value,
self.max))))

def __str__(self): return str(self.n)
def __repr__(self): return 'Limited(%r, min=%r, max=%r)' %
(self.n, self.min, self.max)

def __int__(self): return int(self._value )
def __float__(self) : return float(self._val ue)

def __add__(self, other): return self._apply(ope rator.add, self,
other)
def __sub__(self, other): return self._apply(ope rator.sub, self,
other)
# a few dozens more methods follow ...

def __radd__(self, other): return self._apply(ope rator.add, other,
self)
def __rsub__(self, other): return self._apply(ope rator.sub, other,
self)
# a few dozens more methods follow ...

@classmethod
def _apply(cls, op, first, second):
minmax = None
if isinstance(firs t, cls):
minmax = first.min,first .max
first = first._value
if isinstance(seco nd, cls):
if minmax is None:
minmax = second.min,seco nd.max
second = second._value
return cls(op(first,se cond), *minmax)
a = Limited(11, 0, 9)
print a+1
print 1+a
print a-1
print 1-a
Needless to say, this is almost two orders of magnitude slower than
the builtin numbers, so you'd better not use it for any serious number
crunching.

HTH,
George
Jun 27 '08 #6
Josip wrote:
I'm trying to limit a value stored by object (either int or float):

class Limited(object) :
def __init__(self, value, min, max):
self.min, self.max = min, max
self.n = value
def set_n(self,valu e):
if value < self.min: # boundary check
self.n = self.min
if value self.max:
self.n = self.max
else:
self.n = value
n = property(lambda self : self._value, set_n)

This works, except I would like the class to behave like built-in types, so
I can use it like this:

a = Limited(7, 0, 10)
b = math.sin(a)

So that object itself returns it's value (which is stored in a.n). Is this
possible?
Why not make it a function?

function assignLimited(v alue, vmin, vmax):
value = max(vmin, value)
value = min(vmax, value)
return value
a = assignLimited(7 , 0, 10)
Seems like it solves your problem relatively cleanly.
Note: I also removed min/max variables because they would mask the built-in
min/max functions.

-Larry
Jun 27 '08 #7
Why not make it a function?
>
function assignLimited(v alue, vmin, vmax):
value = max(vmin, value)
value = min(vmax, value)
return value
a = assignLimited(7 , 0, 10)
Seems like it solves your problem relatively cleanly.
Note: I also removed min/max variables because they would mask the
built-in min/max functions.

-Larry
Yes, the simple solution is often the best. Still, I'm going for object
oriented solution because I want the value and it's limits to be kept
together as I'll have many such values with different limits. Storing all
the limits in caller namespace is not really an option.

Jun 27 '08 #8
Why not make it a function?
>
function assignLimited(v alue, vmin, vmax):
value = max(vmin, value)
value = min(vmax, value)
return value
a = assignLimited(7 , 0, 10)
Seems like it solves your problem relatively cleanly.
Note: I also removed min/max variables because they would mask the
built-in min/max functions.

-Larry
Yes, the simple solution is often the best. Still, I'm going for object
oriented solution because I want the value and it's limits to be kept
together as I'll have many such values with different limits. Storing all
the limits in caller namespace is not really an option.


Jun 27 '08 #9
I bet you didn't even try this, unless your definition of "works"
includes a "RuntimeErr or: maximum recursion depth exceeded". Here's a
a working version:
Actually, the version I'm using is somewhat bigger. I removed docstrings and
recklessly stripped away some methods to make it shorter concise and
incorrect.
For (most) math.* functions it suffices to define __float__, so the
above works. For making it behave (almost) like a regular number,
you'd have to write many more special methods:
http://docs.python.org/ref/numeric-types.html.
Here's a possible start:
(...)

Yes, this is very close to what I was looking for. It implements all the
functionality except asssigning values. And speed is not an issue for my
application.
Thanks.

Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
2112
by: Ehud Shabtai | last post by:
Hi, I would like to store samples of data which are gathered from about 500 devices in mysql. Each device has its own data which changes over time. The data may be integer or float. The queries I'm interested in our something like: "show me when the data from device X was greater than 70 and the data from device Y was greater than 90".
30
1548
by: Alf P. Steinbach | last post by:
The C++ FAQ item 29.5 (this seems to be strongly related to C), at <url: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.5> mentions that <quote> C++ guarantees a char is exactly one byte which is at least 8 bits, short is at least 16 bits, int is at least 16 bits, and long is at least 32 bits. </quote>
6
2557
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically,...
12
3914
by: Alfonso Morra | last post by:
I have the ff code for testing the concept of storing objects: #include <vector> #include <iostream> using namespace std ; class MyClass { public: MyClass(){
7
3627
by: Dave | last post by:
I have a system that basically stores a database within a database (I'm sure lots have you have done this before in some form or another). At the end of the day, I'm storing the actual data generically in a column of type nvarchar(4000), but I want to add support for unlimited text. I want to do this in a smart fashion. Right now I am...
6
3186
by: (PeteCresswell) | last post by:
User wants to go this route instead of storing pointers in the DB and the documents outside. Only time I tried it was with only MS Word docs - and that was a loooong time ago - and it seemed to me like there were performance issues at the time. How about the different types? The MS docs I would expect Access to differentiate and handle...
7
5125
by: Ian Boyd | last post by:
Customer wanted us to figure out why their database was growing at an astronomical rate. We broke down the various fields making up a table, and we found that the ..LB file was using about 1k per row, where the average length of the two combined CLOB fields in the table was 12 bytes (4 bytes standard deviation). So i hex edited the .lb...
3
2031
by: RSH | last post by:
Hi, I have a situation where I have created an object that contains fields,properties and functions. After creating the object I attempted to assign it to a session variable so i could retrieve the information it contained on another page. This was significant because I am initially loading the data from the database, then storing relevent...
44
2192
by: vippstar | last post by:
n1256.pdf (C99 TC3), 5.2.4.1 Translation limits p1 says: Does that mean that *any* program using an array of two or more elements other than char is allowed to be rejected by an implementation? For example, int main(void) { int array; return 0; }
0
7502
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7434
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7946
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7457
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1921
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
744
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.