Skip to content Skip to sidebar Skip to footer

Is It Possible To Transform Default Class Dunder Methods Into Class Methods?

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

Solution 1:

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

classCube:def__init__(self, volume):
        DummyCube().cubes.append(self)
        self.volume = volume

Solution 2:

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.

classDummyCube:
    cubes = []

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

classCube:
    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 :)

Post a Comment for "Is It Possible To Transform Default Class Dunder Methods Into Class Methods?"