简体   繁体   中英

Is it possible to make a instance of a class callable

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM