pythonclassprogram-entry-pointbloom-filter

Python main function in class


I'm new to python and the main() method and class def's are confusing me. I'm trying to create a bloom filter and my program keeps terminating because I don't think I'm calling things correctly.

    class BloomFilter(object):
        def __init__(self, numBits, numHashFunctions):
            self.numBits = numBits
            self.bitArray = [0] * numBits
            self.hash = bloomFilterHash(numBits, numHashFunctions)

        def insert(self, key):

        def lookup(self, key):

        def rand_inserts(self,num):

        def main(): #not sure if i should put this inside or outside class
            bloomfilter = BloomFilter(100,5)
            bloomfilter.rand_inserts(15)

    if __name__ == '__main__':   
        BloomFilter().main()

So if I wanted to create a bloom filter with 100 numBits and 5 hash functions, should i call that under the if __name__ == '__main__' or under def main()? I'm not sure if I'm calling these correctly as I'm much more familiar with Java. thanks!

    def main():
        bloomfilter = BloomFilter(100,5)
        bloomfilter.rand_inserts(15)

Solution

  • the name == '__main__' clause is to make sure your code only runs when the module is called directly, not, for instance, if you are importing something from the module in another module. main() is not a special method for a python class, so I believe your objective here, in a simplified way, is the following:

    class BloomFilter(object):
        def __init__(self, numBits, numHashFunctions):
            self.numBits = numBits
            self.bitArray = [0] * numBits
            self.hash = bloomFilterHash(numBits, numHashFunctions)
    
    
    if __name__ == '__main__':
        # creates an instance of the class
        bloomfilter = BloomFilter(100,5)
        # apply some method to instance...
        bloomfilter.rand_inserts(15)