I have an uniform list of objects in python:
class myClass(object): def __init__(self, attr): self.attr = attr self.other = None objs = [myClass (i) for i in range(10)]
Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function (for plotting that data for example)
What is the pythonic way of doing it,
attr=[o.attr for o in objsm]
?
Maybe derive list and add a method to it, so I can use some idiom like
objs.getattribute("attr")
?
getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute. If the attribute does not exist, then it would be created.
A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.
attrs = [o.attr for o in objs]
was the right code for making a list like the one you describe. Don't try to subclass list
for this. Is there something you did not like about that snippet?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With