Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extremely dynamic class properties

Tags:

python

class

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?

like image 327
Ryan Saxe Avatar asked Dec 09 '22 12:12

Ryan Saxe


1 Answers

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:

>>> bar = type('Foo', (), dict(l))()
>>> bar.first
'foo'
>>> bar.second
'bar'
>>> bar.anything
'you get the point'

type() returns a class, not an instance, hence the extra () at the end.

like image 74
TerryA Avatar answered Dec 26 '22 18:12

TerryA