0

I am creating an empty dictionary inside a class and then I am trying to give the variables inside the dictionary some value. As shown in the code below. In the end, I am trying to print the dictionary values in the console but I receiving errors

In the editor:

import numpy as np
class A:
    def __init__(self, variables = {}):
        self.variables = {}
        if ("leng") in variables:
            self.variables["leng"] = variables["leng"]
        else:
            self.variables["leng"] = np.array([10,])


        if ("width") in variables:
            self.variables["width"]= variables["width"]
        else:
            self.variables["width"] = np.array([10,])

In the Console:

variables.items()


>>>"leng" : 10
>>>"width" : 10
  • 1
    `variables` doesn't exist, your argument is called `variable`, singular. It's also a [mutable default argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument), which you probably don't want – roganjosh Jun 10 '19 at 14:02
  • 1
    what error are you getting? full traceback please. What is `variables`? – Paritosh Singh Jun 10 '19 at 14:02
  • Variables is my dictionary which is initially empty but later I initialize two keys in it called 'leng' and 'width' . I am trying to print my dictionary in the console – Gia sharma Jun 10 '19 at 14:06
  • Where are you doing `print(variables.items())`? *Inside* the class, or *Outside* of it? Because once you get outside the class, the variable goes out of scope - you'd then need to create an instance `a = A(vars)` and then `print(a.variables.items())`. – Green Cloak Guy Jun 10 '19 at 14:09
  • This seems like a vague problem. Are you calling the class via an instance? By instance, I mean an object of the class, like m=A() and then m.variables – Amit Amola Jun 10 '19 at 14:11

1 Answers1

0

Just use an object to call class items.

m=A() and then m.variables

Amit Amola
  • 2,301
  • 2
  • 22
  • 37