0

the string class in python has following feature:

s = "Hello"
s.upper()
[Out] "HELLO"
s
[Out] "Hello"

This means, calling the class instance without arguments returns a string. I would like to implement this feature in my own class. The result should look like this:

a = MyClass(13.4,"Value 1")
a
[Out] 13.4
a.title()
[Out] "Value 1"

Is this possible and how can I implement it? Thank's for your help.

Jan
  • 171
  • 1
  • 1
  • 8
  • Implement the `__str__` and/or `__repr__` methods. You're not "calling" anything when doing `s`, Python is getting a printable representation of the object. – deceze Jun 29 '17 at 09:18
  • See [here](https://stackoverflow.com/questions/1535327/how-to-print-a-class-or-objects-of-class-using-print) – P. Siehr Jun 29 '17 at 09:21
  • @deceze: Thank's for your help and sorry for the duplicate. I think I did not find the other answer because I did not know that __repr__ is the solution of my problem. – Jan Jun 29 '17 at 09:48

2 Answers2

1

Here you have a working code. You need to implement __repr__:

In [19]: class MyClass(object):
    ...:     def __init__(self, value, string):
    ...:         self.value = value
    ...:         self.string = string
    ...:     def __repr__(self):
    ...:         return str(self.value)
    ...:     def title(self):
    ...:         return self.string
    ...:

In [20]: a = MyClass(13.4, "Value 1")

In [21]: a
Out[21]: 13.4

In [22]: a.title()
Out[22]: 'Value 1'
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
  • Thanks for the quick answer. Is it also possible to assign the value a in a similar way (a = 15.2) ? I think the problem will be that a points to 15.2 afterwards and not to MyClass anymore?! – Jan Jun 29 '17 at 09:37
  • @Jan If you assign `a = 15.2`, instance `a` will be overwritten. If you want to change the value contained by instance `a` you should: `a.value = 15.2`. – Carles Mitjans Jun 29 '17 at 09:38
0

You'll need to implement the __repr__ method of the class.
Reference: Purpose of __repr__ in python and python docs.