1

I want to overwrite the get method for a variable in a class. (I'm not sure how to explain it otherwise.)

I've tried looking on Google, but nothing really helped me.

My code:

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

print(Class().foo)

I want to make it so it will print out ' '.join(Class().foo) by default instead of just Class().foo.

Is there something that you can add to the code to make it like that?

Professor Dragon
  • 217
  • 1
  • 4
  • 14

2 Answers2

2

You probably want to use the @property wrapper instead of defining foo as an attribute. You can store the parameters you want to print in a private class variable and then define the behavior of the foo to return the string join.

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

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

print(Class().foo)
# prints:
foo bar
James
  • 32,991
  • 4
  • 47
  • 70
2

You can override __getattribute__ to do that:

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)

Output:

huey dewey louie
['tom', 'jerry', 'spike']

Python 2 version:

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)

Note that it is easy to get into infinite loops with overriding __getattribute__, so you should be careful.

There's almost certainly a less scary way to do this, actually, but I can't think of it right now.

gmds
  • 19,325
  • 4
  • 32
  • 58