[Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?
Cameron Simpson
cs at zip.com.au
Sat Jan 23 18:38:38 EST 2016
On 23Jan2016 16:25, boB Stepp <robertvstepp at gmail.com> wrote:
>On Sat, Jan 23, 2016 at 12:55 PM, boB Stepp <robertvstepp at gmail.com> wrote:
>> I still would like to do this via a method, but I am currently stuck
>> on how to replace ??? with the attribute name I would like to insert:
>>
>> class Dog(object):
>> ...
>>
>> def add_attribute(self, attribute_name, attribute_value):
>> self.??? = attribute_value
>>
>> If I write something like:
>>
>> unique_marking = 'blue right eye'
>> our_dog.add_attribute(unique_marking, 'blue right eye)
>>
>> I cannot get ??? to be unique_marking. Instead, show_attributes()
>> will give from .__dict__, 'attribute_name', instead of what I would
>> like to replace it with, unique_marking. But I have not given up yet!
>
>I think I now have this nuked out. I am only just now realizing how
>powerful .__dict__ is:
[... working code ...]
>Wow! So much power for so little code!
Sure. But also note that in the real world you will hardly ever work on
.__dict__ directly. If I were collecting a lot of _arbitrary_ features like
.unique_marking I would put them all in some internal attribute:
class Dog(object):
def __init__(self, name):
self.name = name
self.features = {}
def add_feature(self, feature_name, feature_value):
self.features[feature_name] = feature_value
(Note, deliberately avoiding the term "attribute" here.)
Also, Python provideds the functions setattr and getattr to _avoid_ directly
accessing .__dict__:
setattr(self, attribute_name, attribute_value)
because not all objects use .__dict__ to store this stuff. Generally the dunder
names are to be avoided: not that they should never be used, but they tend to
be mechanism which has "public" exposure elsewhere, eg __dict__ vs
getattr/setattr. For exactly the same reason as other OO stuff: because the
internal implementation is not always __dict__.
So you might access __dict__ internally for introspection, but you would more
commonly use getattr (and outsiders should _always_ use getattr!) Or, of
course, if the attribute name is known at coding time, with the better .name
syntax:
v = dog.__dict__['unique_feature']
v = getattr(dog, 'unique_feature')
v = dog.unique_feature
from least desired to most desired. BTW, when the attribute exists these all
return the same thing, but when the attribute does no exist they all raise
different kinds of exception.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list