Python - 如何在使用类'get'方法时返回不同的值? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我想覆盖类中变量的get方法。 (我不知道如何解释它。)

我试过在谷歌上看,但没有什么真正帮助我。

我的代码:

class Class():
    self.foo = ['foo','bar']

print(Class().foo)

我想这样做它将默认打印出' '.join(Class().foo)而不仅仅是Class().foo

是否有一些东西可以添加到代码中以使其像那样?

python class variables
2个回答
2
投票

你可以覆盖__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__很容易进入无限循环,所以你应该小心。

实际上,实际上几乎可以肯定这样做不那么可怕,但我现在想不到它。


1
投票

您可能希望使用@property包装器而不是将foo定义为属性。您可以将要打印的参数存储在私有类变量中,然后定义foo的行为以返回字符串连接。

class Class:
    _foo = ['foo', 'bar']

    @property
    def foo(self):
        return ' '.join(self._foo)

print(Class().foo)
# prints:
foo bar
© www.soinside.com 2019 - 2024. All rights reserved.