[Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?

boB Stepp robertvstepp at gmail.com
Sat Jan 23 17:25:01 EST 2016


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:

>>> class Dog(object):
        def __init__(self, name, breed):
            self.name = name
            self.breed = breed
            self.number_legs = 4
            self.number_tails = 1
            self.number_eyes = 2

        def add_attribute(self, attribute_name, attribute_value):
            self.__dict__[attribute_name] = attribute_value

        def show_attributes(self):
            print("The object,", self.name, "has the following attributes:")
            for attribute_name, attribute_value in self.__dict__.items():
                print(attribute_name, "=", attribute_value)

>>> our_dog = Dog('Copper', 'beagle')
>>> our_dog.show_attributes()
The object, Copper has the following attributes:
number_tails = 1
number_eyes = 2
breed = beagle
number_legs = 4
name = Copper
>>> our_dog.add_attribute('unique_marking', 'blue right eye')
>>> our_dog.show_attributes()
The object, Copper has the following attributes:
number_eyes = 2
breed = beagle
unique_marking = blue right eye
number_tails = 1
number_legs = 4
name = Copper
>>> our_dog.unique_marking = 'blood-shot eyes'    # Just to check that .unique_marking is a correct reference
>>> our_dog.show_attributes()
The object, Copper has the following attributes:
number_eyes = 2
breed = beagle
unique_marking = blood-shot eyes
number_tails = 1
number_legs = 4
name = Copper

Wow!  So much power for so little code!

boB


More information about the Tutor mailing list