使用类变量操作会产生零?

时间:2018-05-14 17:21:42

标签: python python-2.7 oop

我在类中有以下方法:

    def initialize_overlaps(self):
    """Initialize the overlap list for each band_nk """
    for n in range(self.nbands):
        for k in range(self.nkpts - 1):
            for n_prim in range(self.nbands):
                print("Currently overlapping n: " + str(n) + ". k: " +str(k) +". n': " +
                      str(n_prim) + "\t" +str(n/self.nbands) + " percent completed.")

运行它时,循环的索引变化很好,但我不知道为什么操作n/self.nbands总是产生零:

Currently overlapping n: 3. k: 12. n': 10       0 percent completed.
Currently overlapping n: 3. k: 12. n': 11       0 percent completed.
Currently overlapping n: 3. k: 13. n': 0        0 percent completed.
Currently overlapping n: 3. k: 13. n': 1        0 percent completed.
Currently overlapping n: 3. k: 13. n': 2        0 percent completed.
Currently overlapping n: 3. k: 13. n': 3        0 percent completed.
Currently overlapping n: 3. k: 13. n': 4        0 percent completed.

1 个答案:

答案 0 :(得分:1)

这是因为n始终小于self.nbands,因此纯/除法为0。您应该将两个值中的一个转换为float。 print语句中的以下替换将起作用

str(n/float(self.nbands))