0

I want to call a instance of a class directly,

for expample-

class A(Object):
    def __init(self,temp):
        super(A, self).__init__()
        self.val = temp

    def get_val(self):
        return self.val

Now, creating an instance -

my_var = A('something')
print(my_var.get_val())

but i want to print the value only by using -

print(my_var) or print(my_var())

Is this possible?

Aditya Mishra
  • 194
  • 1
  • 13
  • 1
    Possible duplicate of [What is a "callable" in Python?](https://stackoverflow.com/questions/111234/what-is-a-callable-in-python) – OneCricketeer Jun 28 '18 at 13:22
  • Take a look at the `__str__()` and `__repr__()` magic functions of a class. – guidot Jun 28 '18 at 13:23
  • 1
    Related reading: [`__repr__`](https://docs.python.org/3/reference/datamodel.html#object.__repr__), [`__call__`](https://docs.python.org/3/reference/datamodel.html#object.__call__) – Kevin Jun 28 '18 at 13:24

1 Answers1

1

You can override __str__() method. When you are printing an object reference directly, it internally calls obj.__str__(). Hence, you can achieve what you want by overriding the said method.

class A():
    def __init__(self,temp):
        self.val = temp

    def get_val(self):
        return self.val


    def __str__(self):
        return self.get_val()


my_var = A('something')
print my_var

OUTPUT:

something
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86