Are numbers considered objects in python?

I know that numeric values ​​are immutable in python. I also read how the whole thing is an object in python. I just want to know if numeric types are also objects in python. Because if they are objects, then the variables are actually reference variables? Does this mean that if I pass a number to a function and modify it inside the function, then two numeric objects with two references are created? Is there a concept of primitive data types in python?

Note: I also thought of this as objects. But the visualization in python instructor says differnt: http://www.pythontutor.com/visualize.html#mode=edit

def test(a):
    a+=10
b=100
test(b)

      

Or is it a defect in the rendering tool?

+3


source to share


2 answers


Are objects of numeric types?

>>> isinstance(1, object)
True

      

Apparently they are. :-).

Note that you may need to change your mental model slightly object

. It seems to me that you are thinking of object

how what is "mutable" is not. We actually need to think of python names as an object reference. This object can contain references to other objects.

name = something

      



Here the right-hand side is evaluated - all names are split into objects, and the result of the expression (object) is referenced by "name".

Ok, now let's take a look at what happens when you pass something to a function.

def foo(x):
   x = 2

z = 3
foo(z)
print(z)

      

What do we expect from here? First, we create a function foo

. Then we create an object 3

and refer to it by name z

. After that, we will look at the value that z

references and passes that value to foo

. On entry, foo

this value is referenced (local) x

. Then we create object 2 and refer to it by local name x

. Note. x

has nothing to do with global z

. These are independent links. Just because they were referring to the same object when they entered a function, that doesn't mean that they have to refer to that function all the time. We can change what the name refers to at any time using the assignment operator.

Please note, your + = example may sound complicated, but you can think of a += 10

how a = a + 10

if it helps in this context. For more information on + = check: When is "i + = x" different from "i = i + x" in Python?

+8


source


Everything in Python is an object that includes numbers. There are no "primitive" types, only built-in types.



The numbers, however, are immutable. When you perform a number operation, you create a new number object.

+3


source







All Articles