'Python - How to create an object class whose number of attributes are determined by what is inputted to it?
Forgive me if this idea is simply a poor one to start with, or is poorly worded. Google was not returning anything useful, at least for my attempts to search for this type of issue.
What I would like to do is to create a class of objects whose number of attributes, and their values, depend on what is fed into them?
for example, if I have a starting set of data points [a,b,c,d,e], I would like to create five objects, one for each letter, and have each object also have an attribute for each letter. So five objects, each with 5 attributes.
This is easy enough to hard code by hard, but I would love to find a method so that if you input a larger set of data points, say [a,b,c,d,e,f,g,h,i,j,k], you would then get ten objects, each with 10 attributes.
I'm unsure how to implement this or whether it is possible.
Solution 1:[1]
You can use kwargs and the dict attribute from the class. kwargs is a dictionary of key-word arguments, for instance if you pass "x=10" in the argument, you get a dict of {'x': 10}. You can then use this dictionary in order to initialize the class methods. This code below shows how to do this:
class Point:
def __init__(self, **kwargs):
for key, value in kwargs.items():
self.__dict__[key] = value
def __repr__(self):
out = ""
for k in self.__dict__.keys():
out += "{} = {}\n".format(k, self.__dict__[k])
return out
p1 = Point(x=10, y=20, z=30)
print(p1)
p2 = Point(x=10, y=20, z=30, w=40)
print(p2)
I just modified the repr from the class to make the print more readable.
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 | Guilherme Correa |
