user12239061
user12239061

Reputation:

Handle a object like dictionary

Hi everybody i have some issues with this code. I would to handle the class object diz like a dictionaries and implement the class with add method. In my code python runs a syntax error at line 17. May someone help me? My final goal is to add and remove any quantity of fruit using add method.Sorry if i was wrong to post the question but it's my first posting here

class FruitBasket:
    def __init__(self,diz):
        self.diz = diz
    def __repr__(self):
        return '{}'.format(self.diz)
    def __add__(self,frutto):
        self.frutto = frutto
        return self.diz[self.frutto] += 1

diz = {"banana" : 3 , "apple" : 5,"mango" : 1, "orange" : 2}

diz = FruitBasket(diz)

print(diz)

Upvotes: 1

Views: 43

Answers (2)

Frank
Frank

Reputation: 2029

If you want to have a full dictionary-like behaviour (icluding indexing etc.) you can inherit from python dict:

class FruitBasket(dict):
    pass


diz=FruitBasket()
diz = {"banana" : 3 , "apple" : 5,"mango" : 1, "orange" : 2}

diz = FruitBasket(diz)

print(diz)
# {'apple': 5, 'orange': 2, 'banana': 3, 'mango': 1}

print(diz['apple'])
# 5

This way it is de facto a dictionary but you can extend it with your own functionality.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

You cannot do both += and return in the same line

return self.diz[self.frutto] += 1

Instead you could do

self.diz[self.frutto] += 1
return self.diz[self.frutto]

Upvotes: 2

Related Questions