To create a property in a class you simply do self.property = value
. I want to be able to have the properties in this class completely dependent on a parameter. Let us call this class Foo
.
instances of the Foo
class would take a list of tuples:
l = [("first","foo"),("second","bar"),("anything","you get the point")]
bar = Foo(l)
now the instance of the Foo
class we assigned to bar
would have the following properties:
bar.first
#foo
bar.second
#bar
bar.anything
#you get the point
Is this even remotely possible? How?
There are two ways to do this:
Use
setattr
like this. This approach is feasible if you only need to process the initial list once, when the object is constructed.Define a custom
__getattr__
method. Preferably, you would store the properties in adict
for faster lookup, but you can also search the original list. This is better if you want to later modify the list and want this to be reflected in the attributes of the object.setattr works.
These are called attributes, rather than properties. With that in mind, the method
setattr()
becomes more obvious:This takes each key-value pair in
l
and sets the attributek
on the new instance ofFoo
(self
) tov
.Using your example:
Something like this?
Using
setattr
you can do this by passing in the list and just iterating through it.I thought of another answer you could use using
type()
. It's completely different to my current answer so I've added a different answer:type()
returns a class, not an instance, hence the extra()
at the end.