Passing parameters of python black magic and passing python magic

Source: Internet
Author: User

Passing parameters of python black magic and passing python magic

We have all heard that in the python world, everything is an object.
How can we say that everything is an object? The most common:

> class A: pass> a = A()

We say that a is an object.
Now that everything is ready, A is actually an object. 3 is also an object. True is also an object. "Hello" is also an object.
> Def Func (): pass
O ~ Yee and Func are also objects.
What is the transfer between objects? Let's take a look at the following two simple examples:

> a = 3> b = a> b = 3 + 1> print b4> print a3> a = []> b = a> b.append(1)> print a[1]> print b[1]

Isn't it true that all python objects are passed by reference? Is Mao's first B not 3?
Okay. In fact, in python implementation, objects are divided into mutable and immutable.
The Object Classification mentioned here refers to the implementation of this feature. Rather than attributes of objects.
What is immutable? Indicates that the object itself cannot be changed. Remember that the object itself cannot be changed.
What is an object that cannot be changed?
A simple example:

> a = (1,2,3)> a[0] = 10  

TypeError: 'tuple' object does not support item assignment
The elements of the tuples cannot be changed after initialization. That is to say, the tuples have the immutable feature.
It is very simple. mutable is variable. For example:

> a = {}> a[0] = 10

With the two examples above, I believe you have a basic understanding.
In the python world, what are immutable and mutable features?
In short, all basic types are immutable, while all objects are mutable.
For example:Int, float, bool, tupleAll are immutable.
For example:Dict, set, list, classinstanceAll are mutable.
The problem arises. Since the basic type is immutable, why isn't the top B = 3 + 1 throwing an exception like tuple?
The reason is that the int + operation will execute its own _ add _ method. The _ add _ method returns a new object.
The fact is that when the basic type is changed, it does not change itself, but creates a new object. The final return is a reference to the new object.
How to prove it?
We can use a function called id. This function returns a unique id of the object (the current implementation can be indirectly understood as the memory address of the object ).
Let's take a look:

> a = 3> id(a)140248135804168> id(3)140248135804168> id(4)140248135804144> a = a + 1> id(a)140248135804144

You see? After a = a + 1 is executed, id (a) has changed.
Why is this happening?
In fact, a = a + 1 goes through two processes:

  • 1. a + 1
  • 2. a value assignment

Step 2 is just a reference change. The focus is on step 1. A + 1, then python will actually call a. _ add _ (1 ).
For the implementation logic of the int type _ add _ function, a new int object is created and returned.
Do you find anything special?
The value of id (4) is equal to id (3 + 1 ). This is only a special optimization for int and bool in python. Do not assume that all other basic types point to the same object as long as the values are the same.
There is a special example, str. Make a simple experiment:

> a = "hello"> id(a)4365413232> b = "hell"> id(b)4365386208> id(a[:-1])4365410928> id(a[:-1])4365413760

Have you seen it? Although the values are the same, they still point to (create) different objects, especially the last two sentences. Even if the same operation is executed, different objects are still created.
Is python so silly that a new object is created every time?
No. It only caches "some" results. We can try again:

> a = "hello"> ret = set()> for i in range(1000):  ret.add(id(a[:-1]))> print ret{4388133312, 4388204640}

Have you seen it? Python is still smart. However, I have not studied the specific caching mechanism in depth. I hope you can share it with me.
Return to our topic again. How are parameters transmitted in python?
The answer is: Pass the reference.
If you are using a static language (such as me), you may use the following example to challenge me:

def fun(data):  data = 3a = 100func(a)print a # 100

Is it not Nima reference transfer? Is the value of a not changed after Mao executes func (? Here we made a basic mistake in Dynamic Language.
Data = 3, which is a semantic value assignment statement of dynamic languages. Do not understand C ++ or other languages.
Let's see if we pass in a mutable object:

> def func(m):  m[3] = 100> a = {}> print a{}> func(a)> print a{3:100}

Now, do you know how to pass parameters? Good tips, advanced!
Like many languages such as C ++, js, swift..., python function declaration supports default parameters:
Def func (a = []): pass
What does it mean? Read your own books!
What I want to say here is, if our default parameter is a mutable object, what black magic products will be generated?
Let's look at the following functions:

def func(a=[]):  a.append(3)  return a

Some colleagues may say: I am going! So simple? To cheat the code?
But is it really that simple? Let's take a look at the following call results:

> print func()[3]> print func()[3,3]> print func()[3,3,3]

Is this really the result you want?
No, what I want is [3], [3], [3]!
Why? Let's take a look at the magic of id:

def func(a=[]):  print id(a)  a.append(3)  return a> print func()4365426272[3]> print func()4365426272[3, 3]> print func()4365426272[3, 3, 3]

Do you understand? Originally in python, * the default parameter is not created every execution! *
Now you can think about why the code that you have laughed at (at least me) should be one more thing:

def func(a=None):  if a is None:    a = []

Here we mention =, is:
=: Compare values
Is: Compares whether the left and right sides are the same object. A is B => id (a) = id (B)
OK, let's move on!
We all know that in python, we can define indefinite parameters as follows:
Def func (* args, ** kv): pass
What do you not know? Read books!
What is the situation of args and kv? Is it mutable or immutable?
Once again, ask for the id () artifact:

def func(*args):  print id(args)> a = [1,2]> print id(a)4364874816> func(*a)4364698832> func(*a)4364701496

See it? In fact, args will also generate a new object. However, the value is the input parameter. Will each item be copied?
Let's take a look:

def func(*args):  print id(args[0])> a = [1,2]> print id(a[0])140248135804216> func(*a)140248135804216

The answer is No. The value points to the object referenced by the original list (a), just like the normal list Value assignment.
So why?
That's how python source code is written .......
At last, do you remember the sentence I said?
Immutable restricts the immutable object.
This means that the immtable of an object only limits whether its attributes can be changed without affecting the referenced objects.
See the following example:

> a = [1,2]> b = (a,3)> b[1] = 100TypeError: 'tuple' object does not support item assignment> print b([1, 2], 3)> b[0][0] = 10> print b([10, 2], 3)

Finally, I have an object that should be mutable, but I want it to have immutable-like features, can it?
The answer is, you can simulate it!
As mentioned earlier, immutable limits that its own attributes cannot be changed.
Then, we can change the function by redefining (reloading) the attribute to simulate the immutable feature.
Can python be used? O ~ Yee
In python, there are two functions: _ setattr _ and _ delattr __. It is executed when the object property is assigned and deleted.
Then we can simulate immutable through simple overloading:

class A:  def __setattr__(self, name, val):    raise TypeError("immutable object could not set attr")

The above is the introduction of the python black magic, hope to help you learn.

Articles you may be interested in:
  • Passing function parameters in python (parameters with asterisks are described)
  • Python def Function Definition, use, and parameter passing implementation code
  • Python advanced tutorial-multiple methods for passing function parameters
  • Keep up with the passing of summary parameters of Python
  • Analyze the Passing Process of method parameters in Python using examples
  • Summary of passing parameters in python
  • Examples of Variable Parameter definitions and parameter passing methods of Python Functions
  • Introduction to parameter passing and variable length parameters of functions in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.