[Tutor] Using new style classes and __slots__
kent37 at tds.net
Sun Sep 25 04:15:37 CEST 2005
Your method signatures are off. Should be
def setA(self, value)
So when you write self.a = 20 you are passing self as the um parameter. Actually I don't know why you don't get an exception for passing too many arguments?
And you don't need setattr, just write
Strange.a = property(...)
Oh wait, I get it - you are passing bound methods to property(). So um is bound to the instance when you access self.getA. Use Strange.getA instead of self.getA, then use the normal signatures.
But I don't get why you are doing this at all? What does it buy you over the standard form of
def setA(self, value):
self.__a = value
a = property(getA, setA)
self.a = 20
One more note below.
Liam Clarke wrote:
> Well, I got setattr() and property() working together nicely, but with
> a weird side effect.
> class Strange(object):
> def getA(um, self):
> print "What is", um
> return self.__a
> def setA(um, self, value):
> print um, "turns up here as well."
> self.__a = value
> def __init__(self):
> setattr(Strange, "a", property(self.getA, self.setA))
> self.a = 20
>>>>c = Strange()
> <__main__.Strange object at 0x01166290> turns up here as well.
> 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!
It is passing self twice, because you are using a bound method as the property method rather than an unbound method.
> I'm getting the feelin I may need to venture into comp.lang.Python
> with this sort of stuff.
> Liam Clarke
> 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:
>>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
>><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
>>Hmm, may have to learn even more about classes and their internals.
> Tutor maillist - Tutor at python.org
More information about the Tutor