<分区>
我想覆盖类中变量的 get 方法。 (我不确定如何解释。)
我试过在 Google 上查找,但没有任何帮助。
我的代码:
class Class():
self.foo = ['foo','bar']
print(Class().foo)
我想让它默认打印出 ' '.join(Class().foo)
而不仅仅是 Class().foo
。
是否可以在代码中添加一些东西来实现它?
<分区>
我想覆盖类中变量的 get 方法。 (我不确定如何解释。)
我试过在 Google 上查找,但没有任何帮助。
我的代码:
class Class():
self.foo = ['foo','bar']
print(Class().foo)
我想让它默认打印出 ' '.join(Class().foo)
而不仅仅是 Class().foo
。
是否可以在代码中添加一些东西来实现它?
最佳答案
你可以覆盖 __getattribute__
来做到这一点:
class Thingy:
def __init__(self):
self.data = ['huey', 'dewey', 'louie']
self.other = ['tom', 'jerry', 'spike']
def __getattribute__(self, attr):
if attr == 'data':
return ' '.join(super().__getattribute__(attr))
else:
return super().__getattribute__(attr)
print(Thingy().data)
print(Thingy().other)
输出:
huey dewey louie
['tom', 'jerry', 'spike']
Python 2 版本:
class Thingy(object):
def __init__(self):
self.data = ['huey', 'dewey', 'louie']
self.other = ['tom', 'jerry', 'spike']
def __getattribute__(self, attr):
if attr == 'data':
return ' '.join(super(Thingy, self).__getattribute__(attr))
else:
return super(Thingy, self).__getattribute__(attr)
print(Thingy().data)
print(Thingy().other)
请注意,覆盖 __getattribute__
很容易陷入无限循环,因此您应该小心。
实际上,几乎可以肯定有一种不那么可怕的方法,但我现在想不出。
关于Python - 使用类 'get' 方法时如何返回不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55895895/