Regarding __slots__ and other stuff: A couple of questions

dave berk dave.brk at gmail.com
Thu Mar 27 10:27:42 EDT 2008


I'm new to Python. I'm trying to understand the type/class/object(instance)
model. I have read here:
http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html
and here:
http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html
as well as here:
http://users.rcn.com/python/download/Descriptor.htm

There are still a couple of issues I'm unclear about. I'll be very happy if
one of you could help me.
*first:*
Why doesn't this works?
<code>
>>> class C(object):
... __slots__ = ['foo', 'bar']
... class_attr = 'class attribute'
...
>>> c = C()
>>> c.foo = 'foo'
>>> c.bar = 'bar'
>>> c.bar, c.foo
('bar', 'foo')
>>> c.__slots__
['foo', 'bar']
>>> c.__slots__.append('eggs')
>>> c.__slots__
['foo', 'bar', 'eggs']
>>> c.eggs = 'eggs'
Traceback (innermost last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'eggs'
</code>

*second:*
what happens here? Why can I write to spam using the class object but not
the using the instance?
<code>
>>> class C(object):
... __slots__ = ['foo', 'bar']
... class_attr = 'class attribute'
...
>>> C.spam = 50
>>> C.spam
50
>>> C.spam = 56
>>> c = C()
>>> c.spam = 55
Traceback (innermost last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object attribute 'spam' is read-only

>>> C.spam = 55
>>> C.spam
55
</code>

*Third:*
<code>
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""

def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name

def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val

def __set__(self, obj, val):
print 'Updating' , self.name
self.val = val
class A(object):
def __init__(self):
self.x = RevealAccess(10, 'var "x"')
self.y = 5
class B(object):
x = RevealAccess(10, 'var "x"')
y = 5

>>> a = A()
>>> b = B()
>>> a.x
<__main__.RevealAccess object at 0x00BAC730>
>>> a.x = 55
>>> b.x
Retrieving var "x"
10
>>> b.x = 55
Updating var "x"
>>>
</code>
Why the descriptor works only when created as a static variable and not
as an instance variable?

I'm sure all this questions stem from my lack of understanding python object
model. But, please, what am I missing?

Thanks
Dave
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080327/ffe9c7b0/attachment.html>


More information about the Python-list mailing list