【问题标题】:Python - How to return a different value when using a class 'get' method? [duplicate]Python - 使用类“get”方法时如何返回不同的值? [复制]
【发布时间】:2019-09-17 15:17:52
【问题描述】:

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

我尝试在 Google 上查找,但没有任何帮助。

我的代码:

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

print(Class().foo)

我想让它默认打印出' '.join(Class().foo),而不仅仅是Class().foo。

有什么可以添加到代码中的东西吗?

【问题讨论】:

  • 你想要print(Class().foo) print 'foo bar'?

标签: python class variables


【解决方案1】:

您可以覆盖 __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__ 很容易陷入无限循环,因此您应该小心。

实际上,几乎可以肯定有一种不那么可怕的方法,但我现在想不出。

【讨论】:

  • 嗯...这似乎不适合我。
  • @ProfessorDragon 什么不起作用,具体来说?
  • 嗯,它只是打印了这个:['huey', 'dewey', 'louie'] 和 ['tom', 'jerry', 'spike']。
  • @ProfessorDragon 你在用 Python 2 吗?
  • 是的。 (我需要评论更多字符,所以我添加了这个。)
【解决方案2】:

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

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

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

print(Class().foo)
# prints:
foo bar

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2013-08-17
    • 1970-01-01
    • 2017-10-28
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多