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?
__init__method is an initializer. That's what happens when you create an instance of that class. It's in no way a "callable" in the traditional sense. Please read the docs, or tell us specifically what you're trying to achieve.<class '__main__.neg'>when I ran it.__call__method (not shown here) can be used to make instances callable.