[Tutor] Class: property? function list?
Sean 'Shaleh' Perry
Mon, 01 Oct 2001 00:49:52 -0700 (PDT)
On 01-Oct-2001 Run-Sun Pan wrote:
> Dear all,
>  --- "property" in class ???
> Is there any "property" in class? For example,
> mc = myclass()
> mc.hitcount = 100 #<===== user input
> x = mc.hitcount
> print x
> In the above example there's no validation
> whatsoever. As long as the 100 is passed to
> .hitcount, no matter it's a string or even
> other object type, it will be past to x.
> I want to have this .hitcount value validated
> before it is returned to other variable x. In
> some other object-oriented languages you can
> define "properties" for a class for this purpose.
> Is there such device in python ?
The best I have seen done is to define __setattr__ and __getattr__.
def __setattr__(self, name, vale):
if name == 'hitcount':
if value < 0 or value > 1000:
value = 0
self.dict['hitcount'] = value
def __getattr__(self, name):
and in __init__() you just initialize dict and any variables you maintain.