[Tutor] Using new style classes and __slots__
ml.cyresse at gmail.com
Sun Sep 25 03:36:48 CEST 2005
Well, I got setattr() and property() working together nicely, but with
a weird side effect.
def getA(um, self):
print "What is", um
def setA(um, self, value):
print um, "turns up here as well."
self.__a = value
setattr(Strange, "a", property(self.getA, self.setA))
self.a = 20
>>> c = Strange()
<__main__.Strange object at 0x01166290> turns up here as well.
>>> print c.a
What is <__main__.Strange object at 0x01166290>
<__main__.Strange object at 0x01166290>
To my uneducated eye, it looks like it's passing self twice! Returning
um.__a works exactly the same as self.__a!
I'm getting the feelin I may need to venture into comp.lang.Python
with this sort of stuff.
On 9/25/05, Liam Clarke <ml.cyresse at gmail.com> wrote:
> > You might want to learn more about the whole property mechanism then. property() is actually a bit of sugar over a deeper mechanism. Also there is an interesting idiom for creating properties using @apply (in Python 2.4) - look for Benji York's comment in this recipe:
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
> Thanks Kent. Just looking at that above recipe, I'm not too sure how
> the @ decorators work.
> From what I understand, it defines would turn apply() into a function
> that returns the various get/sets?
> Also found something interesting with property(), if it's called in
> __init__ you get
> >>> a.a
> <property object at 0x011598C8>
> whereas called outside __init__ it works normally.
> This is a hassle for me because I'm a lazy typist, so I've been using
> setattr() to pull attribute names out of a list. And the first
> argument setattr() requires is an object, and self doesn't work
> outside of a method, and using the class name leads to no attribute
> being set.
> Hmm, may have to learn even more about classes and their internals.
> Liam Clarke
More information about the Tutor