dimanche 19 juin 2016

Making a class callable in python


I came to know we can also make class as callable without implementing the __call__() function, and I am trying to write some thing like that but I got stuck: below is my code

class neg:
    def __init__(self): # Classes are callables too
        self.val = 54545 
    def __repr__(self): 
        return str(self.val)

if __name__=='__main__':
       x=neg
       print(x) #print(neg()) also shows nothing
       #added by Merlin
       print('value of x:', x ) 

Executing the above does nothing, it doesn't print, What i am missing here?

The example i read to make class callable:

class Negate:
    def __init__(self, val): # Classes are callables too
    self.val = -val # But called for object, not work
    def __repr__(self): # Instance print format
    return str(self.val)
     actions = [square, sobject, pobject.method, Negate] # Call a class too
    for act in actions:
    print(act(5))

I fixed the main it does work, but when they say a class are callable then it shouldn't be neg() wasn't it?


Aucun commentaire:

Enregistrer un commentaire