M
mshiltonj
I'm trying to find the preferred python idiom for access arbitrary
fields of objects at run time.
For example, say I have an object the business code will do
*something* with three arbitrary fields at a given time, but I don't
know what the three fields are at run time. In perl, I'd do something
like this:
sub three_fields{
my $self = shift;
my @fields = @_;
foreach my $field (@fields)
{
my $value = $self->$field; # this is the one I'm
interested in
[...]
}
}
In python, I'm doing something like this:
def three_fields(self, field1, field2, field3):
for field in (field1, field2, field3):
value = eval('self.' + field) # this is the one I'm
interested in
[...]
This seems to do what I expect it to do. I'm wondering if that's the
preferred or standard way to do this in python. I wasn't sure how to
tease the answer to this question out of Google.
Thanks.
fields of objects at run time.
For example, say I have an object the business code will do
*something* with three arbitrary fields at a given time, but I don't
know what the three fields are at run time. In perl, I'd do something
like this:
sub three_fields{
my $self = shift;
my @fields = @_;
foreach my $field (@fields)
{
my $value = $self->$field; # this is the one I'm
interested in
[...]
}
}
In python, I'm doing something like this:
def three_fields(self, field1, field2, field3):
for field in (field1, field2, field3):
value = eval('self.' + field) # this is the one I'm
interested in
[...]
This seems to do what I expect it to do. I'm wondering if that's the
preferred or standard way to do this in python. I wasn't sure how to
tease the answer to this question out of Google.
Thanks.