这个问题在这里已有答案:
我想覆盖类中变量的get方法。 (我不知道如何解释它。)
我试过在谷歌上看,但没有什么真正帮助我。
我的代码:
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__
很容易进入无限循环,所以你应该小心。
实际上,实际上几乎可以肯定这样做不那么可怕,但我现在想不到它。
您可能希望使用@property
包装器而不是将foo
定义为属性。您可以将要打印的参数存储在私有类变量中,然后定义foo
的行为以返回字符串连接。
class Class:
_foo = ['foo', 'bar']
@property
def foo(self):
return ' '.join(self._foo)
print(Class().foo)
# prints:
foo bar