'creating an object from a class in python in shortest form
I have this class in python, for crating an empty Box type dictionary, Box is a library for extending ways of working with dictionaries:
from box import Box
class Ipsm():
def __init__(self):
self.ipsm = Box(default_box=True)
def ipsmAddElement(self, box_dots):
def validIpsmAddElementLine(self, box_dots):
if box_dots:
return True
if validIpsmAddElementLine(self, box_dots):
eval(f"self.ipsm.{box_dots}")
if __name__ == "__main__":
box = Ipsm()
print(box.ipsm) #{}
box.ipsmAddElement("IP.nested_elem")
print(box.ipsm) #{'IP': {'nested_elem': {}}}
box.ipsm.IP.nested_elem = "127.0.0.1"
print(box.ipsm.IP.nested_elem) #127.0.0.1
Is it possible to re-write the class (adding another method...) so that I don't have to use "box.ipsm" to get to this dictionary to add my keys. For instance, just doing box.IP.nested_elem = "127.0.0.1", should get me to that result.
Solution 1:[1]
Classes do not work this way. Referring to an object will always get you that object, and you use object.attribute or object.method to access things within it.
As commenter jasonharper suggested, you should probably subclass Box, by using this syntax:
class MyBox(Box):
# ...
Your new subclass will inherit everything in Box and will work just like it, but with anything you add included.
Edit:
If you're not adding any other methods or attributes to Box, no need to create a new class, just instantiate Box and it will work exactly as you want it to.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joshua Levin |
