我的类中的一个方法是工作,但另一个具有相同语法的方法不起作用(python)

时间:2018-03-03 21:21:35

标签: python python-3.x attributeerror

class Calculate():

def set_total_cost(self):
total_cost = 1000
self.__total_cost = total_cost

def get_total_cost(self):
return self.__total_cost

def set_down_pmt(self):
down_pmt = 0.25
self.__down_pmt = down_pmt

def get_down_pmt(self):
return self.__down_pmt


test = Calculate()
test.set_total_cost()
test.set_down_pmt()

print(test.get_total_cost())
print(test.get_down_pmt())

总费用功能有效,但是预付款方式没有,我收到此错误:

  

属性错误:'计算'对象没有属性' _Calculate__down_pmt'

2 个答案:

答案 0 :(得分:1)

不要忘记Python中的缩进很重要

以下是您的课程应该是什么样的:

class Calculate():

    def set_total_cost(self):
        total_cost = 1000
        self.__total_cost = total_cost

    def get_total_cost(self):
        return self.__total_cost

    def set_down_pmt(self):
        down_pmt = 0.25
        self.__down_pmt = down_pmt

    def get_down_pmt(self):
        return self.__down_pmt

如果get_down_pmt()方法没有缩进,则它不属于您的Calculate类。

答案 1 :(得分:0)

您很可能遇到空格问题。

class Calculate():
    def set_total_cost(self):
        total_cost = 1000
        self.__total_cost = total_cost
    def get_total_cost(self):
        return self.__total_cost
    def set_down_pmt(self):
        down_pmt = 0.25
        self.__down_pmt = down_pmt
    def get_down_pmt(self):
        return self.__down_pmt

test = Calculate()
test.set_total_cost()
test.set_down_pmt() 
print(test.get_total_cost())
print(test.get_down_pmt())

输出:

  

1000

     

0.25