[Tutor] Class: property? function list?

Andrei Kulakov ak@silmarill.org
Mon, 01 Oct 2001 03:45:11 -0400


On Mon, Oct 01, 2001 at 02:38:53AM -0500, Run-Sun Pan wrote:
> Dear all,
> 
> [1] --- "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 ?
> 
> [2] --- list all variables and functions of
>         myclass
> 
> Is there a way to get a list of all the "names" 
> of all the variable and function names of my
> own class ?
> 
> Thx in advance.  
> 
> pan

You could do this:

class MyClass:
    def set_count(self, count):
        if type(count) != type(1):
            print "error"
        else:
            self.hit_count = count

mc = MyClass()
mc.set_count("test")    # prints error
mc.set_count(5)         # valid

 - Andrei

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org