Newbie: Functions and class

Shu-Hsien Sheu sheu at bu.edu
Wed Oct 29 16:32:19 EST 2003


Hi,

After 2 months of learning in Python, the most difficult part is the 
object part. Though I can get most of my works done using very simple 
classes, I don't think I get the essence of it. Right now I am thinking 
of wrirting a class like:

class hittable(object):
    def __init__(self):
        self.table = [{}, {}, {}, {}]
    def build(<some parameter>):      #some modification to the dictionary
        <some codes>
    def search(self, aa):
        if aa == 0:
            <do modification "build" to self.table[0]>
        if aa == 1:
            <do modification "build" to self.table[1]>

I have trouble implementing the above in real code. I can only get 
something by making a seperate function outside the class:

 >>> def build(dd, i):
    dd.setdefault(i, {})
    return dd
 >>> class hittable(object):
    def __init__(self):
        self.table = [{}, {}, {}, {}]    #0:peptides, 1: nucleotides, 
2:metals, 3:others
    def search(self, i):
        self.table[i] = build(self.table[i], i)      
 >>> kk = hittable()
 >>> kk.search(3)
 >>> kk.table
[{}, {}, {}, {3: {}}]

And couldn't find a way to integrate the "build" function into a class 
method:

 >>> class hittable(object):
    def __init__(self):
        self.table = [{}, {}, {}, {}]
    def build(self, i):
        self.table[i].setdefault(i, {})
    def search(self, i):
        self.table[i] = self.build(i)
 >>> kk = hittable()
 >>> kk.search(3)
 >>> kk.table
[{}, {}, {}, None]

I think I can imagine the above code won't work, though couldn't find a 
solution to it.

What am I missing here?

Thanks!

-shushien








More information about the Python-list mailing list