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

Viewed 100

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.

2 Answers

No idea if this solves your problem. But to call your getattribute you need to include parentheses.

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

I see. I'm still learning Python, so my suggestions might not be that great. Don't worry this will be the last one ^^. I just noticed that this might be what you are looking for.

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):
        self.volume = volume
        DummyCube.cubes.append(self)
 
a = Cube(1)
b = Cube(2)
c = Cube(3)

print(DummyCube.__getattribute__('volume'))
print(DummyCube.cubes[0].volume)
print(DummyCube.cubes[1].volume)
print(DummyCube.cubes[2].volume)

Btw. I still don't get how this works :)

Related