1

Let's say I have the following class:

class Human(object):
    def __init__(self, name, last_name):
        self.name = name
        self.last_name = last_name

    def get_last_name(self):
        return self.last_name

And I know I can define a __repr__ method for it:

    def __repr__(self):
        return "Human being, named " + str(self.name) + " " + str (self.last_name)

However, what if I want to define a separate representation for a lastname method, too? I.e., if this is a sample:

>>> me = Human("Jane", "Doe")
>>> me
Human being, named Jane Doe
>>> me.get_last_name()
'Doe'

…then I want the last output be not only the string 'Doe' itself but something like Human being's last name is Doe – how can it be done? How to define a __repr__ (or a __str__) method for a method?

Thanks.

A S
  • 1,195
  • 2
  • 12
  • 26

2 Answers2

1

You can not use a special attribute for a function or another attribute. In this case since you have self.last_name in your __init__ function, instead of returning it back in get_last_name() you can apply expected changes on last_name here and return the expected format.

class Human(object):
    def __init__(self, name, last_name):
        self.name = name
        self.last_name = last_name

    def get_last_name(self):
        # return expected format

And you can directly access last_name if you want to see the raw data.

me = Human("Jane", "Doe")
print(me.last_name)
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • I.e., in order to have both `'Doe'` and `Human being's last name is Doe`, I have to define two different methods, something like `get_last_name()` and `get_last_name_gorgeously()`? No other way around? – A S Feb 26 '16 at 08:55
  • @AS Sorry I cant got you. When you want separate representations you need to use separate callers. Other wise the result would be same. Or maybe based on different input you produce separate output. – Mazdak Feb 26 '16 at 09:03
1

If you want readable representation override __str__ method. For obtain unambiguous output override __repr__

Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25
  • Yeah, got that [already](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python), thanks! – A S Feb 26 '16 at 09:01