问题
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