Is it possible to transform default class dunder methods into class methods?

半城伤御伤魂 提交于 2020-06-17 02:52:47

问题


To give you some context, yesterday I came across this post. I found the problem quite interesting, so I tried to find a solution that would keep the syntax as close as possible to what was asked. Here is what I came up with:

class DummyCube:
    cubes = []

    @classmethod
    def __getattribute__(cls, name):
        print('is this called?')
        attributes = [getattr(cube, name) for cube in cls.cubes]

        return attributes


class Cube:
    def __init__(self, volume):
        DummyCube.cubes.append(self)
        self.volume = volume


a = Cube(1)
b = Cube(2)
c = Cube(3)

print(DummyCube.__getattribute__('volume'))
print(DummyCube.volume)

I think my approach is way too complicated (or just generally not very good), especially compared to the currently accepted answer, but fortunately, that's not really relevant to what I would like to know.

My approach fails, because DummyCube.volume raises an AttributeError: type object 'DummyCube' has no attribute 'volume', which is of course true, but I don't understand why my custom __getattribute__ class method is not called. Invoking the method directly works. Is it not possible to do this at all? What am I missing here? As far as I understand, __getattribute__ is what is called first, when using the '.'-notation, but the error traceback does not let me confirm this.

来源:https://stackoverflow.com/questions/62039065/is-it-possible-to-transform-default-class-dunder-methods-into-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!