Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding variably named fields to Python classes

Tags:

python

I have a python class, and I need to add an arbitrary number of arbitrarily long lists to it. The names of the lists I need to add are also arbitrary. For example, in PHP, I would do this:

class MyClass {

}

$c = new MyClass();
$n = "hello"
$c.$n = array(1, 2, 3);

How do I do this in Python?

I'm also wondering if this is a reasonable thing to do. The alternative would be to create a dict of lists in the class, but since the number and size of the lists is arbitrary, I was worried there might be a performance hit from this.

If you are wondering what I'm trying to accomplish, I'm writing a super-lightweight script interpreter. The interpreter walks through a human-written list and creates some kind of byte-code. The byte-code of each function will be stored as a list named after the function in an "app" class. I'm curious to hear any other suggestions on how to do this as well.

like image 223
Carson Myers Avatar asked May 05 '10 04:05

Carson Myers


People also ask

How do I add an attribute to a class in Python?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.

How do you declare a variable in Python class?

Create Class VariablesA class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.

What is the __ add __ method in Python?

Python __add__() method adds two objects and returns a new object as a resultant object in Python. The below example returns a new object, Python3.

Can a class have parameters Python?

Python Class Object At first, you put the name of the new object which is followed by the assignment operator and the name of the class with parameters (as defined in the constructor). Remember, the number and type of parameters should be compatible with the parameters received in the constructor function.


1 Answers

Use setattr.

>>> class A(object):
...     pass
... 
>>> a = A()
>>> f = 'field'
>>> setattr(a, f, 42)
>>> a.field
42
like image 114
wRAR Avatar answered Sep 23 '22 01:09

wRAR