Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic syntax for appending an arbitrary class object list property

Tags:

python

Is there an analog of setattr() that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so?

This is a trivialized version of what I'm doing currently:

foo = SomeClass()
...
attr = "names"
value = "Eric"
values = getattr(foo, attr)
values.append(value)
setattr(foo, attr, values)

This seems clunky and inefficient.

Edit: this assumes that foo.names (or whatever arbitrary value might be assigned to the attr variable) is in fact a list.

like image 965
heydenberk Avatar asked Jul 13 '10 23:07

heydenberk


People also ask

What does __ class __ mean in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

How do you create a class property in Python?

Python property() function returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.

What is class object and attribute in Python?

A class attribute is a variable that belongs to a certain class, and not a particular object. Every instance of this class shares the same variable. These attributes are usually defined outside the __init__ constructor. An instance/object attribute is a variable that belongs to one (and only one) object.


1 Answers

The setattr call is redundant, if foo.names is indeed a list (if it's something else, could you please clarify?). getattr(foo, attr).append(value) is all you need.

like image 116
Alex Martelli Avatar answered Nov 15 '22 15:11

Alex Martelli