[Texas] Trouble with one of the Koans
alexander.j.robbins at gmail.com
Fri Sep 3 23:06:03 CEST 2010
I think the basic idea here is that you can define a __setattr__
method on your object, which is later used by python for assignments.
The __setattr__ method gives you more control over assignment into
your object. This __setattr__ basically says:
If the attr_name the user is trying to assign to ends with comic, then
prepend my_ to the attribute name.
If the attr_name the user is trying to assign to ends with pie, then
prepend a_ to the attribute name.
Then assign the provided value to the newly computer attribute name.
instance = PossessiveSetter()
instance.comic = 'Texas'
At this point, if I lookup instance.comic, nothing is there. The
__setattr__ method intercepted my assignment and put it into my_comic.
instance.my_comic == 'Texas'
Does that make any more sense than the koan?
On Fri, Sep 3, 2010 at 9:57 AM, Mark Sharp <msharp at sfbr.org> wrote:
> In the about_attribute_access.py of the Python 3.1 koans, the following
> class is defined. Although I can get the tests to pass, I am missing the
> Do you know of any discussion of the koans? I have not located one.
> Alternatively can you direct me to someone that would be willing to explain
> what this class is teaching?
> class PossessiveSetter(object):
> def __setattr__(self, attr_name, value):
> new_attr_name = attr_name
> if attr_name[-5:] == 'comic':
> new_attr_name = "my_" + new_attr_name
> elif attr_name[-3:] == 'pie':
> new_attr_name = "a_" + new_attr_name
> object.__setattr__(self, new_attr_name, value)
> def test_setattr_intercepts_attribute_assignments(self):
> fanboy = self.PossessiveSetter()
> fanboy.comic = 'The Laminator, issue #1'
> fanboy.pie = 'blueberry'
> self.assertEqual(__, fanboy.a_pie)
> prefix = '__'
> self.assertEqual("The Laminator, issue #1", getattr(fanboy, prefix +
> R. Mark Sharp, Ph.D.
> Director of Primate Records Database
> Southwest National Primate Research Center
> Southwest Foundation for
> Biomedical Research
> P.O. Box 760549
> San Antonio, TX 78245-0549
> Telephone: (210)258-9476
> e-mail: msharp at sfbr.org
> Texas mailing list
> Texas at python.org
More information about the Texas