是否可以将默认的class dunder方法转换为class方法? [英] Is it possible to transform default class dunder methods into class methods?

查看:49
本文介绍了是否可以将默认的class dunder方法转换为class方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了给您提供一些背景信息,昨天我遇到了这篇文章.我发现这个问题很有趣,因此我尝试找到一种解决方案,以使语法尽可能地接近所要求的内容.这是我想出的:

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.

我的方法失败了,因为 DummyCube.volume 引发了 AttributeError:类型对象'DummyCube'没有属性'volume',这当然是正确的,但是我没有不明白为什么未调用我的自定义 __ getattribute __ 类方法.直接调用该方法即可.根本不可能做到这一点吗?我在这里想念什么?据我了解, __ getattribute __ 是使用'.'表示法时首先被调用的方法,但是错误回溯无法让我确认这一点.

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.

推荐答案

我明白了.我仍在学习Python,所以我的建议可能不是那么好.别担心,这将是最后一个^^.我只是注意到这可能就是您要寻找的.

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

这篇关于是否可以将默认的class dunder方法转换为class方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆