-5

This is from the Python docs. I don't understand this, can someone give some examples?

If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this.

I tried to make an example of this but failed. When I run the program below it prints 1, so the variable is not inaccessible. When would it be?

class Base(object):
    __slots__ = 'a'

    def __init__(self):
        self.a = 1

class Subclass(Base):
    __slots__ = 'a'

    def __init__(self):
        super(Subclass, self).__init__()
        print self.a

Subclass()
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
user2352151
  • 81
  • 1
  • 5
  • Excerpt is fairly straight-forward. Exactly what part of it you do not understand? – Łukasz Rogalski May 28 '16 at 17:31
  • I tried putting together an example to answer your question and discovered the opposite of what the docs said, so I edited it into your question and now I'm also interested to see what answers people have. – Alex Hall May 28 '16 at 17:41
  • the instance variable defined by the base class slot is inaccessible,b = Base() print b.a I thought the b.a is inaccessible,what the inaccessible is? – user2352151 May 28 '16 at 21:12

1 Answers1

2

When I run the program below it prints 1, so the variable is not inaccessible.

You actually have two a instance variables here. The one defined by Base is not accessible through attribute access; for an object of type Subclass, all accesses to self.a, including the one inside Base.__init__, go to the instance variable defined by Subclass.

If you retrieve the Base.a descriptor manually, you can access the slot defined by Base:

>>> x = Subclass()
1
>>> Base.a.__get__(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: a
>>> Base.a.__set__(x, 2)
>>> Base.a.__get__(x)
2
>>> Subclass.a.__get__(x)
1

As you can see, Base.a and Subclass.a are independent, despite sharing the same name.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • If subclass does not have __slots__, x = Subclass(); Base.a.__get__(x) will work, the doc mean this? I always thought is b = Base() ; then b.a is not accessable!! – user2352151 May 28 '16 at 21:48