Mozein
Mozein

Reputation: 807

adding dictionary values from class

I have the class planets that stores in a dictionary Key which is the name of the planet, and value which is the size of the planet, and then add all the values in the dictionary and print it

this is my class

 class planets:
    def store(self, name, mass):
        aDict[self.name] = self.mass

    def add(self):
        return sum(aDict.values())


planets.store("Sun",50)

planets.store("Mercury",7)

print(planets.add())

I am expecting to get an answer of 57, however I am getting an error which is:

TypeError: store() missing 1 required positional argument: 'mass'

How to fix that problem?

Upvotes: 0

Views: 2018

Answers (1)

Yang
Yang

Reputation: 202

planets is a class, def store(self, name, mass): is a instance method. You need to make a instance of planets first to use it's instance methods.

p = planets()
p.store("Sun",50)
p.store("Mercury",7)
print(p.add())

Second problem, you have to use mass to refer the parameter mass not self.mess. self.mess is a property of planets object. And, you need to initialize the aDict property in the __init__ method. So you can define the class using below codes.

class planets:
    def __init__(self):
        self.aDict = {}

    def store(self, name, mass):
        self.aDict[name] = mass

    def add(self):
        return sum(self.aDict.values())

Upvotes: 3

Related Questions