Home .items() doesn't work in my created class
Reply: 2

.items() doesn't work in my created class

Hugues Lamothe
1#
Hugues Lamothe Published in 2018-02-13 18:17:44Z

I wrote this script:

class MonDictionnaire:
    def __init__(self):
        self.dictionnaire = {}
    def __add__(self, objetàajouter):
        nouvelle_valeure = MonDictionnaire()
        nouvelle_valeure.dictionnaire = self.dictionnaire
        nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items()

then I wanted two objects in this class like:

>>>>fruit = MonDictionnaire()
>>> fruit.dictionnaire["pommes"] = 13
>>> fruit.dictionnaire["poires"] = 12
>>> fruit.dictionnaire["pruneau"] = 11
>>> legume = MonDictionnaire()
>>> legume.dictionnaire["poireau"] = 10
>>> legume.dictionnaire["panet"] = 9

then I just wanted to add my two objects like:

>>> fruit = fruit + legume

but the shell return me the following error message:

Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
fruit = fruit + legume
File "D:\Python\Dictionnaire.py", line 9, in __add__
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items())
AttributeError: 'MonDictionnaire' object has no attribute 'items'

and I don't get why as my created class is a dictionnary???!!! thank you so much for helping me!!!

heemayl
2#
heemayl Reply to 2018-02-13 18:27:51Z

You have defined the instance attribute:

self.dictionnaire = {}

whereas in objetàajouter.items() you're trying to get the items method of the instance itself, which is not present.

You need to explicitly specify the attribute:

objetàajouter.dictionnaire.items()

Also, were you meant to subclass dict?

WisdomWolf
3#
WisdomWolf Reply to 2018-02-13 18:28:25Z

Looks like your issue is with this line:

nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items()

When you call: fruit = fruit + legume your class is trying to call .items() on legume. I think this change should work as you expect:

nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.dictionnaire.items()
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302529 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO