为了给你一些背景信息,昨天我遇到了这个帖子 https://stackoverflow.com/q/62031547/5472354。我发现这个问题非常有趣,所以我尝试找到一种解决方案,使语法尽可能接近所要求的内容。这是我想出的:
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)
我认为我的方法太复杂(或者通常不是很好),特别是与当前接受的答案相比,但幸运的是,这与我想知道的内容并不真正相关。
我的方法失败了,因为DummyCube.volume
提出一个AttributeError: type object 'DummyCube' has no attribute 'volume'
,这当然是真的,但我不明白为什么我的习惯__getattribute__
类方法未被调用。直接调用该方法就可以了。难道这根本不可能吗?我在这里缺少什么?据我所理解,__getattribute__ https://docs.python.org/3/reference/datamodel.html#customizing-attribute-access是使用“.”符号时首先调用的内容,但错误回溯不允许我确认这一点。
不知道这是否能解决您的问题。但要打电话给你的获取属性你需要包含括号。
class Cube:
def __init__(self, volume):
DummyCube().cubes.append(self)
self.volume = volume
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)