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?

1
  • you want print(Class().foo) print 'foo bar'?
    – QIFENG LI
    Apr 29, 2019 at 1:16

2 Answers 2

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.

6
  • Hmm... that doesn't seem to work for me. Apr 29, 2019 at 3:30
  • @ProfessorDragon What doesn't work, specifically?
    – gmds
    Apr 29, 2019 at 3:34
  • Well, it just prints this: ['huey', 'dewey', 'louie'] and ['tom', 'jerry', 'spike']. Apr 29, 2019 at 3:38
  • @ProfessorDragon Are you using Python 2?
    – gmds
    Apr 29, 2019 at 3:39
  • Yes. (I need the comment to be more characters so I'm adding this.) Apr 29, 2019 at 3:43
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.