I think you're trying to do two different things here.
First, you want to get a particular ball by name. For that, gnibbler already gave you the answer.
Then, you want to get one of the ball's attributes by name. For that, use getattr
:
the_ball = next(b for b in list_of_balls if b.name == sys.argv[1])
the_value = getattr(the_ball, sys.argv[2])
print('ball {}.{} == {}'.format(sys.argv[1], sys.argv[2], the_value)
Also, your class
definition is wrong:
class ball(self, size, color, name):
self.size = size
self.color = color
self.name = name
You probably meant for this to be the __init__
method inside the ball
class, not the class
definition itself:
class ball(object):
def __init__(self, size, color, name):
self.size = size
self.color = color
self.name = name
However, you may want to reconsider your design. If you're accessing attributes dynamically by name more often than you're accessing them directly, it's usually better just to store a dict
. For example:
class Ball(object):
def __init__(self, size, color, name):
self.name = name
self.ball_props = {'size': size, 'color': color}
list_of_balls = [Ball(10, 'red', 'Fred'), Ball(20, 'blue', 'Frank')]
the_ball = next(b for b in list_of_balls if b.name == sys.argv[1])
the_value = the_ball.ball_props[sys.argv[2]]
Or you may even want to inherit from dict
or collections.MutableMapping
or whatever, so you can just do:
the_value = the_ball[sys.argv[2]]
Also, you may want to consider using a dict
of balls keyed by name, instead of a list:
dict_of_balls = {'Fred': Ball(10, 'red', 'Fred'), …}
# ...
the_ball = dict_of_balls[sys.argv[1]]
If you've already built the list
, you can build the dict
from it pretty easily:
dict_of_balls = {ball.name: ball for ball in list_of_balls}