Listing attributes of a namedtuple subclass

I have a small class that extends namedtuple, but the property of __dict__its instances always returns empty.

Point = namedtuple('Point', 'x y')
p1 = Point(20, 15)
print(p1, p1.__dict__)
# Point(x=20, y=15) OrderedDict([('x', 20), ('y', 15)]) <--- ok

class SubPoint(Point): pass
p2 = SubPoint(20, 15)
print(p2, p2.__dict__)
# SubPoint(x=20, y=15) {} <--- why is it empty?

p2has attributes but its __dict__empty. They are listed correctly with dir(), though, which is strange. Note that this works correctly when SubPointextending the vanilla class.

What happens and how do I list attributes in my instance of a subclass?

+5
source share
3 answers

, __slots__ , , __dict__, __slots__. ( , __dict__ namedtuple dict, @property.)

docs:

__slots__ , . __dict__, __slots__ ( ).

, __slots__ , __dict__ , , __dict__.

:

class A:
    __slots__=  ('a', 'b')

    @property
    def __dict__(self):
        print ('inside A')
        return self.__slots__         

class B(A):
    pass

print(B().__dict__)

print ('-'*20)

class B(A):
    __slots__ = ()
print(B().__dict__)

:

{}
--------------------
inside A
()
+4

__slots__ = () , . , __slots__ , .

Point = namedtuple('Point', 'x y')
p1 = Point(20, 15)
print(p1, p1.__dict__)
# Point(x=20, y=15) OrderedDict([('x', 20), ('y', 15)]) <--- ok

class SubPoint(Point):
    __slots__ = ()
p2 = SubPoint(20, 15)
print(p2, p2.__dict__)
# SubPoint(x=20, y=15) OrderedDict([('x', 20), ('y', 15)]) <--- fixed

.

0
list(A.__annotations__.keys())
0
source

Source: https://habr.com/ru/post/1534186/


All Articles