Skip to content Skip to sidebar Skip to footer

Difference Between Operators And Methods

Is there any substantial difference between operators and methods? The only difference I see is the way the are called, do they have other differences? For example in Python conca

Solution 1:

If I understand question currectly...

In nutshell, everything is a method of object. You can find "expression operators" methods in python magic class methods, in the operators.

So, why python has "sexy" things like [x:y], [x], +, -? Because it is common things to most developers, even to unfamiliar with development people, so math functions like +, - will catch human eye and he will know what happens. Similar with indexing - it is common syntax in many languages.

But there is no special ways to express upper, replace, strip methods, so there is no "expression operators" for it.

So, what is different between "expression operators" and methods, I'd say just the way it looks.


Solution 2:

Your question is rather broad. For your examples, concatenation, slicing, and indexing are defined on strings and lists using special syntax (e.g., []). But other types may do things differently.

In fact, the behavior of most (I think all) of the operators is constrolled by magic methods, so really when you write something like x + y a method is called under the hood.

From a practical perspective, one of the main differences is that the set of available syntactic operators is fixed and new ones cannot be added by your Python code. You can't write your own code to define a new operator called $ and then have x $ y work. On the other hand, you can define as many methods as you want. This means that you should choose carefully what behavior (if any) you assign to operators; since there are only a limited number of operators, you want to be sure that you don't "waste" them on uncommon operations.


Post a Comment for "Difference Between Operators And Methods"