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?
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?
You can also write:
attr=(o.attr for o in objsm)
This way you get a generator that conserves memory. For more benefits look at Generator Expressions.
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__
Then you can test what type is with type() or if is a method with callable().
python - How to extract from a list of objects a list of specific attribute? - Stack Overflow
python - How do i access and object attribute inside a list of objects given certain index? - Stack Overflow
Get attributes from a 2D list (or array) of objects?
If you have the slice, you can iterate over it in a comprehension:
[obj.attr for obj in slice]
where slice is
a[2::2,::2] a[:,2] a[4:,4:]
etc.
More on reddit.comExtract listS of attributes from list of objects in python - Stack Overflow
What is the best method to extract attributes from a list of Python objects?
Can I use a different approach besides list comprehensions?
I'm using the plex python library to get some info from my plex server.
What I wanted to get was the path of a movie.
I tried to use dir(movie_object), vars(movie_object), and movie_object.__dict__ to try and find all of the movie attributes, and to see where the path was stored.
But there was no attribute that contained the file path information.
In the end I found it under movie_object.location by inspecting the object in the VSCode debugging tools.
Why does VSCode show the location attribute, but dir, vars, or __dict__ do not show it?
Is there a way to reliably get ALL of an objects attributes in python?
A list comprehension would work just fine:
[o.my_attr for o in my_list]
But there is a combination of built-in functions, since you ask :-)
from operator import attrgetter
map(attrgetter('my_attr'), my_list)
are you looking for something like this?
[o.specific_attr for o in objects]
In Python, to access object attribute the syntax is
<object instance>.<attribute_name>
In your case, [index].
As Paul said, use dir(<object_instance>[index]) to get all attribute, methods associated object instance.
You can also use for loop to iterate over
for <obj> in <object_list>:
<obj>.<attribute_name>
Hope it helps
You can access the dict (a.k.a Hashtable) of all attributes of an object with:
ListObj[i].__dict__
Or you can only get the names of these attributes as a list with either
ListObj[i].__dict__.keys()
and
dir(ListObj[i])
I have a rather simple question but I haven't been able to find an answer so far: if I have a 2D list of objects, how can I extract all the values from a common attribute?
This is some class:
class Foo():
def __init__(self, attr):
self.attr = attrFor a 1D list, it's really simple:
array = [Foo(i) for i in range(6)] [obj.attr for obj in array]
This will display: [0, 1, 2, 3, 4, 5].
For a multidimensional list, though, this won't work. A solution would be using loops or lists of comprehension to extract the attributes from each column or line. However, slices allow us to access a specific region of a multidimensional list.
So, let's say you have a 6x6 list (or ndarray) of objects, and you want to access the attributes at [4:,4:], or even better, you want to slice the list in a non-contiguous way and then get the attributes of all object elements in the pattern. Is that possible?
Check this image from the numpy docs to have a visual reference about what I'm talking about (see 2nd and 4th slices).
I'm aiming at being able to use this for a board game in which the board would be sliced into different "tile" groups or patterns and then check the properties of the objects in those tiles.
This is not homework.
Use the built-in function dir().
I use __dict__ and dir(<instance>)
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
print(dir(obj))
# Output:
# obj.__dict__ --> {'phone': '+6661', 'name': 'Chuck Norris'}
#
# dir(obj) --> ['__class__', '__delattr__', '__dict__', '__doc__',
# '__format__', '__getattribute__', '__hash__',
# '__init__', '__module__', '__new__', '__reduce__',
# '__reduce_ex__', '__repr__', '__setattr__',
# '__sizeof__', '__str__', '__subclasshook__',
# '__weakref__', 'name', 'phone']
In hindsight I should've realised the code would think I demanded an attribute from the list itself, not the items inside
Actually, code doesn't "think", it is only executed. And the runtime doesn't "think" either, it just executes the code provided. But those minor conceptual nuances set aside, your diagnostic is right: deck.face looks up the attribute named "face" on the deck (list) object itself.
If your question is "how to print (or collect or do whatever with) the face attribute for each card in deck, the simple solution is to iterate on the list:
for card in deck:
print(card.face)
or if you want to build a list of face values:
faces = [card.face for card in deck]
Now if it's an exercise in OO design, you may want to reconsider the use of a list to represent a "deck" object - a cards deck is actually not a list.
Since each element in deck list is Card Object, hence you need to iterate the list and get the face attribute as given below :
faceList = []
for obj in deck:
faceList.append(obj.face)
print (faceList)
If you want a list of dictionaries of object attributes:
# the list of attributes to get from each object
attrs = ['attr1', 'attr2']
# using dictionary comprehension to generate the list of attributes and their values
attr_vals_dict = [{a:getattr(o, a) for a in attrs} for o in objects]
Output:
[{'attr1': 1, 'attr2': 2}, {'attr1': 3, 'attr2': 4}, {'attr1': 'banana', 'attr2': 'apple'}]
As far as getting the dynamic list of attributes in the first place, that's already been answered here.
Something like
[[getattr(o, a) for a in ['attr1', 'attr2']] for o in objects]
should do it.
In terms of performance, to create a list of ages, [i.get_age() for i in person_list] is about as good as you'll get. The only real way to avoid this is to adjust the mean, median, and mode functions to accept a key parameter (much like the built-in sort function does) so that each function will access the correct attribute of the object. I wouldn't worry about removing that list comprehension though. Unless person_list is huge, and you require this code to run often, and as fast as possible, that would be a premature optimization.
Another way to potentially speed it up would be to have a single function that iterates the list once, and calculates all three statistics in one go. Again though, I would consider that to be premature unless you had a very good reason to optimize that.
Your solution is fine until you run into a situation in which it isn't performing well. Favor readability and simplicity until performance becomes an actual concern (or you have good reason to believe that it will become an actual concern in the near future).
For efficiency's sake, without breaking the parameters of your assignment, the only other thing you can add is __slots__.
Beyond that - in the "real world" - if this were a truly massive list, you would want to do away with the class representation and instead use a Numpy matrix, for which the calculation of summary statistics will be faster due to vectorization.