python - 从字典中的对象访问方法

标签 python python-3.x

是否可以从循环访问外部类方法到字典中? 这里有 2 个示例,一个通过循环访问列表,另一个通过字典访问。第一个完成我想用字典完成的工作(第二个):

ins.py

class Ins:
    def __init__(self, cognome, nome, indirizzo, entrate, spese):
        self.__cognome = cognome
        self.__nome = nome
        self.__indirizzo = indirizzo
        self.__entrate = entrate
        self.__spese = spese

    def get_cognome(self):
        return self.__cognome

    def get_nome(self):
        return self.__nome

    def get_indirizzo(self):
        return self.__indirizzo

    def get_totale(self):
        return str(float(self.__entrate) - float(self.__spese))

    def __str__(self):
        return "Cognome: " + self.__cognome + "\nNome: " + self.__nome + \
                 "\nIndirizzo: " + self.__indirizzo +\
                 "\nEntrate: " + self.__entrate + "\nSpese: " + self.__spese
ins_main_list.py   

import ins
dict = []

def main():
    again = 'y'
    while again.lower() == 'y':
        cognome = input('Inserire Cognome: ')
        nome = input('Inserire Nome: ')
        indirizzo = input('Inserire Indirizzo: ')
        entrate = input('Inserire Entrate: ')
        spese = input('Inserire Spese: ')
        again = input("Continuare con l'inserimento? (Y/N) ")
        print()
        entry = ins.Ins(cognome, nome, indirizzo, entrate, spese)
        dict.append(entry)
    for item in dict:
        print(item)
        print(item.get_totale())
        print()

 main()

ins_main_dict.py

import ins
dict = {}

def main():
    again = 'y'
    while again.lower() == 'y':
        cognome = input('Inserire Cognome: ')
        nome = input('Inserire Nome: ')
        indirizzo = input('Inserire Indirizzo: ')
        entrate = input('Inserire Entrate: ')
        spese = input('Inserire Spese: ')
        again = input("Continuare con l'inserimento? (Y/N) ")
        print()
        entry = ins.Ins(cognome, nome, indirizzo, entrate, spese)
        dict[cognome] = entry
    for item in dict:
        print(dict[item])
        print(item.get_totale())
        print()

main()

正如您在上一个示例中看到的,item.get_totale() 给我一个属性错误。怎么可能进入它?

最佳答案

我认为您应该使用 dict[item].get_totale(),而不是 item.get_totale()item 遍历 dict 的键(字符串),而不是您的自定义类

关于python - 从字典中的对象访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063270/

相关文章:

python - 从另一个对象分配 __len__() 方法

validation - 如何在抽象类级别提供值验证?

python - 胶水 etl 作业 - 使用 create_dynamic_frame.from_options 获取 s3 子文件夹

python - 如何求解积分的极限?

python - 在使用 Python 的 vscode 中,ctrl+F5 总是要求输入 "select environment"

python - 颜色图不随 imshow() 改变

Python 3 将范围转换为列表

python - 简单的网络爬虫非常慢

python - 从 Celery 结果后端 MYSQL 查询结果

python - 运行 Sublime Text 3 插件时保存编辑