Python中为何可将方法用作变量?以sum赋值为例
Great question! This gets right to the core of how Python handles names and objects, so let's break it down clearly.
First, let's look at your code snippet again for context:
n=int(input()) a=list(map(int,input().split())) sum=a[0]
1. Python’s "everything is an object" rule
In Python, every single thing is an object—including built-in functions like sum(). The sum you know as the summation tool isn't some special reserved keyword; it's just a name that points to a function object stored in memory.
2. Variable names are just references, not fixed bindings
Think of variable names like sticky labels you slap on objects. The built-in sum label starts attached to the summation function, but Python lets you peel that label off and stick it to any other object you want. When you write sum=a[0], you're reassigning the sum label to point to the first element of your list a instead of the original function.
This isn't unique to sum—you could do the same with other built-ins too, like:
print = "Oops, I'm a string now!" print(123) # This will throw an error, because `print` no longer points to the print function
3. The catch: You lose access to the original built-in
The tradeoff here is that once you reassign sum to be a variable, you can't use the original sum() function in that scope anymore. If you tried to run total = sum(a) later in your code, Python would try to treat the integer stored in sum as a function, which will throw a TypeError.
A quick best practice note
While Python allows this, it's almost always a bad idea to reuse built-in names as variables. It makes code harder to read (other developers expect sum to be the summation function) and breaks access to a useful built-in tool.
内容的提问来源于stack exchange,提问作者AMBUJ HAKHU

