您可以覆盖 __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__ 很容易陷入无限循环,因此您应该小心。
实际上,几乎可以肯定有一种不那么可怕的方法,但我现在想不出。