【问题标题】:AttributeError: 'str' object has no attribute (function)AttributeError:“str”对象没有属性(函数)
【发布时间】:2016-05-10 03:14:50
【问题描述】:

我正在尝试编写一个面向对象的程序,它允许我输入和存储月收入和账单,并根据需要查看所有数据。我可以成功存储一个对象,但是当我尝试使用我的 view_all 函数时,我得到了这个错误:

在 view_all 打印(item.get_month()) AttributeError: 'str' 对象没有属性 'get_month'

如果您能帮我找出这个问题,我将不胜感激!

# Create a month class

class Month:

    # Use __init__ method to initialize the attributes

    def __init__(self, month, income, tds, pnm, zia, water):
        self.__month = month
        self.__income = income
        self.__tds = tds
        self.__pnm = pnm
        self.__zia = zia
        self.__water = water


    # The set methods accept arguments:

    def set_month(self, month):
        self.__month = month

    def set_income(self, income):
        self.__income = income

    def set_tds(self, tds):
        self.__tds = tds

    def set_pnm(self, pnm):
        self.__pnm = pnm

    def set_zia(self, zia):
        self.__zia = zia

    def set_water(self, water):
        self.__water = water

    # The get methods return the data:

    def get_month(self):
        return self.__month

    def get_income(self):
        return self.__income

    def get_tds(self):
        return self.__tds

    def get_pnm(self):
        return self.__pnm

    def get_zia(self):
        return self.__zia

    def get_water(self):
        return self.__water

    # The __str__ method return's the object's state as a string

    def __str__(self):
        return "Month: " + self.__month + \
               "\nIncome: " + self.__income + \
               "\nTDS: " + self.__tds + \
               "\nPNM: " + self.__PNM + \
               "\nZia: " + self.__zia + \
               "\nWater: " + self.__water

还有主程序:

import Month_Class
import pickle

ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3

FILENAME = 'ruidoso.dat'

def main():
    months = load_months()
    choice = 0
    while choice != QUIT:
        choice = get_menu_choice()

        if choice == ADD_MONTH:
            add_month(months)
        elif choice == VIEW_ALL:
            view_all(months)

    save_months(months)


def load_months():
    try:
        input_file = open(FILENAME, 'rb')
        months_dct = pickle.load(input_file)
        input_file.close
    except IOError:
        month_dct = {}
    return month_dct

def get_menu_choice():
    print()
    print('Menu')
    print('------------------')
    print("1. Add data for a new month")
    print("2. View data for all months")
    print('Any other number saves and quits the program!')
    print()

    choice = int(input('Enter your choice: '))
    while choice < ADD_MONTH or choice > QUIT:
             choice = int(input('Enter a valid choice: '))
    return choice

def add_month(months):
    month = input('Enter the name of the month: ')
    income = input('Total income for this month: ')
    tds = input('TDS Broadband bill total: ')
    pnm = input('PNM bill total: ')
    zia = input('Zia Natural Gas bill total: ')
    water = input('City of Ruidoso bill total: ')

    entry = Month_Class.Month(month, income, tds, pnm, zia, water)

    if month not in months:
        months[month] = entry
        print('The entry has been added')
    else:
        print('That month already exists!')

def save_months(months):
    output_file = open(FILENAME, 'wb')
    pickle.dump(months, output_file)
    output_file.close()


def view_all(months):
    for item in months:
        print(item.get_month())
        print(item.get_income())
        print(item.get_tds())
        print(item.get_pnm())
        print(item.get_zia())
        print(item.get_water())

main()        

【问题讨论】:

  • 仅供参考:在 Python 中使用 getter 和 setter 非常不寻常。
  • @Matthias 这是我们教科书的一部分。真的不经常用吗?
  • 不,不是。当您使用 getter 和 setter 时,您在 Python 中获得了什么优势?只需使用实例属性本身。如果除了设置值之外还有更多的逻辑,建议使用 @property 装饰器。查看this question

标签: python object


【解决方案1】:

你需要以不同的方式遍历字典

for month, item in months.items():
    print(item.get_month())
    ... 

【讨论】:

  • 太棒了。这个问题困扰了我一段时间,感谢您的帮助。
  • 在创建 .dat 文件后出现了另一个小问题。 UnboundLocalError:分配前引用了局部变量“month_dct”。将 .dat 文件中的数据加载到months_dct 字典中似乎存在问题,特别是“return month_dct”这一行。
【解决方案2】:

view_all 方法中,您必须遍历字典:

for key, item in months.iteritems():
    print(item.get_month())

您在 Month 类的 __str__ 方法中遇到其他错误:

"\nPNM: " + self.__PNM + \

正确的是:

"\nPNM: " + self.__pnm + \

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2021-10-04
    • 2019-12-02
    • 2021-09-25
    • 2014-03-04
    • 2013-09-22
    相关资源
    最近更新 更多