Python中的主要功能

时间:2017-02-20 20:16:57

标签: python class main

我是python的新手,而main()方法和类def让我感到困惑。我试图创建一个绽放过滤器,我的程序一直在终止,因为我不认为我正确地调用了东西。

    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()

因此,如果我想创建一个包含100个numBits和5个哈希函数的bloom过滤器,我应该在' if__name __'下调用它。还是在def main下?我不确定我是否正确地调用了这些,因为我对java更熟悉。谢谢!

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

2 个答案:

答案 0 :(得分:2)

name == '__main__'子句是为了确保您的代码仅在直接调用模块时运行,而不是,例如,如果您从另一个模块中的模块导入某些内容。 main()不是python类的特殊方法,所以我认为这里的目标是简化的,如下所示:

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)

答案 1 :(得分:1)

您可能希望将main()放在类之外:

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():
     some_value = Bloomfilter(100, 5)

     some_value.rand_inserts(15)

 main()