13
I am very confused about what is an object and what can behave as an object, see the example I created to illustrate the situation:
def subtrai(x,y):
return (x - y)
class OpeMatematica(object):
def __init__(self, x, y):
self.x = x
self.y = y
def soma(self):
return (self.x + self.y)
soma = OpeMatematica(10,10)
print(soma.soma())
print(subtrai(100, 10))
s = subtrai
print(s(50,10))
s = soma
s.x = 10
s.y = 100
print(s.soma())
I created a function subtrai performing a subtraction and creating a class OpeMatematica with the attributes x and y and a method soma.
In this line:
soma = OpeMatematica(10,10)
print(soma.soma())
I established my class OpeMatematica and invoked the method soma and I got the result 20.
In this line:
print(subtrai(100, 10))
I invoked the function subtrai and I got the result 90.
In this line I discovered something interesting:
s = subtrai
print(s(50,10))
See that I assign the variable s the function subtrai and the same began to assume the behavior of the function subtrai see s(50,10), is as if the function subtrai were an object and could be instantiated, the result of the operation is 40.
And in this line has another curiosity:
s = soma
s.x = 10
s.y = 100
print(s.soma())
Assigns to s the object soma and s became an object of the type OpeMatematica, accessing the attributes x and y and invoking the method soma, the result obtained is 110.
Now I’m confused about what is a Python object, analyzing this code I concluded that everything seems to be a Python object even variables and function, could someone explain to me why Python has this behavior, and what is an object or a class in Python?
I don’t quite understand the purpose of
callable(s)and thehasattr(s, '__call__')could you explain to me?– gato
See if you’ve improved.
– Maniero
I can understand now.
– gato
The function
callableserves to test whether an object can be invoked or not, it returnsTrueorFalse. Therefore it cannot be used to invoke methods/functions nor in Python 2 or in the Python 3.– fernandosavio
@fernandosavio took this part, I was confusing more than helping even.
– Maniero
I think I could change
if hasattr(s, '__call__')forif callable(s)... This way is more correct, despite the discussion be a little long,callablechecks Pyobject in C to see if it can be invoked (I believe this field) andhas_attrmay have problems in specific cases.– fernandosavio