0

I've been trying to create a class that gets the parameter names and subsequent values from the init method of another class. Here's an example of the class I'm trying to get those names from:

class Item(Watcher):
   def __init__(self, iname: str, iid=0):
       super().__init__()
       self.iname = iname
       self.iid = iid

   def __repr__(self):
       return f"{self.iname}"

What I would like for the parent class to do is take the function parameters (in this case, "iname" and "iid", but should work for any function with differing parameter names), as well as the values for those parameters and spit them back out in dictionary form like so:

{"iname": "iname's value", "iid": "iid's value"}

So far, I've tried this (from Getting list of parameter names inside python function):

class Watcher:
    def __init__(self):
        pass
    
    def root(self):
        params = self.__init__.__code__.co_varnames
        a = {}
        for param in params:
            if not param == "self": out[param] = "???"

But this is where I get stuck. I'm not quite sure how to dynamically get the values of init parameters given a string of the parameter's name.

If anyone can help, thanks ahead of time

  • 1
    Do you mean you need to find the run time value of the parameter? – MYousefi Dec 25 '20 at 08:26
  • @MYousefi Yes. Ideally, you should be able to do `item = Item("placeholder").root()` during code execution and get the dictionary `{'iname': 'placeholder', 'iid': 0}` in return – RSyncPlausible Dec 25 '20 at 08:34
  • Item("placeholder") constructor will execute with __init__ then the .root() will be called. By this time __init__ has finished and the Item object is created so there's no runtime information on __init__. – MYousefi Dec 25 '20 at 08:43
  • What is the purpose of this? Maybe that'll help with a solution. – MYousefi Dec 25 '20 at 08:44
  • Oh, well that makes sense. As for the purpose, it's for an extremely bare-bones game which means most of the __init__ parameters for these classes are placeholders now and might be changed in the future. I guess I could try to make a .root() function for each individual class. As for the fact of the lack of runtime information on the __init__, do you know of a way to circumvent getting the parameters from there and instead straight from the actual class (like getting a list of constants in the class) and sort through that? – RSyncPlausible Dec 25 '20 at 09:03
  • Do you know about OOP, inheritance, abstract classes, etc? Also python objects do have __dict__ which gives you the set parameters for the object. – MYousefi Dec 25 '20 at 09:35
  • I think I have a basic understanding of them. I'm somewhat new to Python and have never really used class inheritance until now. I'll have to look more into __dict__, that seems like the way to go. Thanks! – RSyncPlausible Dec 25 '20 at 18:31

0 Answers0