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

问题描述 投票:0回答:2
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())

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

AttributeError:'Calculate'对象没有属性'_Calculate__down_pmt'

python python-3.x attributeerror
2个回答
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类。


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

© www.soinside.com 2019 - 2024. All rights reserved.