Message277740
I was working with descriptors and hit on an error, that I do not understand.
I attach a protocol of my interactive python session that will show you what happened and the session is reproducible:
I had a class employing a descriptor:
class Descriptor(object):
def __init__(self, name):
self.name = name
def __set__(self, instance, val):
print('Updating', self.name, 'for', instance)
instance.__dict__[self.name] = val
class A:
x = Descriptor('x')
def __init__(self, name, x):
self.x = x
self.name = name
def __repr__(self):
return "I am {}".format(self.name)
if defined like this it hits an error when I want to initialize it:
a = A('a', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
File "<stdin>", line 5, in __set__
File "<stdin>", line 7, in __repr__
AttributeError: 'A' object has no attribute 'name'
Updating x for
The error could be fixed by just exchanging the assignments in the __init__ of A:
class A:
x = Descriptor('x')
def __init__(self, name, x):
self.name = name
self.x = x
def __repr__(self):
return "I am {}".format(self.name)
Now a = A('a', 2) works as expected. But this seems weird to me. |
|
Date |
User |
Action |
Args |
2016-09-30 06:31:55 | Sabine.maennel@gmail.com | set | recipients:
+ Sabine.maennel@gmail.com |
2016-09-30 06:31:55 | Sabine.maennel@gmail.com | set | messageid: <1475217115.9.0.838082905984.issue28316@psf.upfronthosting.co.za> |
2016-09-30 06:31:55 | Sabine.maennel@gmail.com | link | issue28316 messages |
2016-09-30 06:31:55 | Sabine.maennel@gmail.com | create | |
|