0

I have a class that makes objects allowing me to access properties of an experimental camera system. I have some configuration properties saved in a dict for where certain cameras should be initially located. As these initial settings may vary I cannot hard code them into the class but need them separate in a text file that I access using the json library.

Is there a way to pass the dict into a class so its key value pairs can be used?

Simplified code

import any_dict_01
import json

data = any_dict_01


class dummy(data):

    def __init__(self):
        self.data = data


    def getDict(self):
        print(self.data)


a = dummy()
a.getDict()

Working Code

based on hints and advice from karl in the comments under the question I figured out how to do it (I hope karl puts his comments as an answer so I can accept it).

import json


data = 'my_rig.txt'


class dummy:

    def __init__(self, data):
        self.data = data


    def getDict(self):
        with open(data) as json_file:
        data = json.load(json_file)
        print(data)


a =dummy()
theDict = a.getDict(data)
Windy71
  • 851
  • 1
  • 9
  • 30
  • 1
    You're nearly there. A typical constructor looks like `def __init__(self, data): self.data = data` – Adam Smith Jul 03 '20 at 06:21
  • `class dummy(data):` -> `class Dummy:` – blakev Jul 03 '20 at 06:24
  • 1
    `data = any_dict_01` does **not** make `data` be any particular `dict` defined by the `any_dict_01` module. It makes `data` be *another name* for that same *module*. – Karl Knechtel Jul 03 '20 at 06:27
  • 1
    Anyway, this question isn't really about classes. The way you get information into the __init__ method is the same way that you get information into *any ordinary function*: by giving it a *parameter*, and passing the information in as an *argument*. – Karl Knechtel Jul 03 '20 at 06:28
  • @KarlKnechtel if you put that as an answer, the 2 comments merged I will accept it as based on that I wrote some code that does work, thank you. – Windy71 Jul 03 '20 at 06:36

3 Answers3

1

Your code would work by fixing the last part like this:

   def __init__(self, data):
      self.data = data

   def getDict(self):
      return self.data

a = dummy(data)
theDict=a.getDict()

You can make the dict accessible with dot notation, as if it were a class instance, like this.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
1
class dummy:
    def __init__(self, my_dict):
        self.my_dict = my_dict
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36
1

By request:

data = any_dict_01 does not make data be any particular dict defined by the any_dict_01 module. It makes data be another name for that same module.

Anyway, this question isn't really about classes. The way you get information into the __init__ method is the same way that you get information into any ordinary function: by giving it a parameter, and passing the information in as an argument.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153